Instruction

by Paweł Paduch published 2020/11/12 09:20:00 GMT+2, last modified 2021-11-19T12:53:41+02:00
.Net threads

This lab aims to familiarize you with the basics of the language c# along with elements of concurrent programming in .net

  1. Introduction
    In 2000, Microsoft introduced the idea of standardizing the software for the Windows platform. Main features of  .net:
    • new libraries
    • new tools
    • independence of the language (VB, C #, C ++, J #, and dozens of others)
    • platform independence thanks to CIL - Common Intermediate Language
    • Linux implementations, e.g. mono or dotGNU
    • fully object oriented
    • The garbage collection is handled by the runtime
    • advanced programming mechanisms ( delegates, reflections, generics, lambdas, LINQ queries, etc.)
    Package and namespace differences:
    • a single package e.g. mscorelib.dll can contain multiple namespaces
    • each namespace can contain multiple types
    A namespace is a semantic grouping of related types found in a package, such as system.IO, System.Data, System.Thread . This makes it easier to understand and organize the types logically.
    A few selected namespaces:
    • System - many useful types related to internal data, environment variables and garbage collection, as well as many common exceptions and attributes.
    • System.Collections - Definition of multiple container types, as well as base types and interfaces, to build custom collections.
    • System.Data, System.data - Communication with relational databases using ADO.NET
    • System.IO - Many types used in file I / O, data compression, and port manipulation.
    • System.Reflection - Types that support runtime type detection as well as dynamic type creation.
    • System.Drawing, System.Windows.Forms - Types Used to Build Windowing Applications Using the Original .Net UI Toolset (Windows Forms)
    • System.ServiceModel - It is used to build distributed applications using WCF API (Windows Communication Foundation)
    • System.Web - It is used to build ASP.NET web applications
    • System.Threading - Numerous types for building multithreaded applications
    • System.Xml - XML-related namespaces
    Types in the namespace can be referenced by their full name, e.g .: System.Threading.Thread or use </ span> using System.Threading and call Thread directly.

  2. First program (0.1 points)
    Start Visual Studio
    Create a new console project named Threads , the name of the solution can be e.g. lab1 or DotNet1
    DotNet1En_01.png

    DotNet1En_02.pngRewrite code below to Program.cs:
    class Program
        {
            static int iterations = 10;
            static int threadCount = 10;
    
            static void PrintSomething()
            {
                Console.WriteLine(Thread.CurrentThread.Name + " Begin printing numbers:");
                Random rand = new Random();
                for (int ii = 0; ii < iterations; ii++)
                {
                    Console.Write("{0}, ", ii); //print number
                    Thread.Sleep(rand.Next(0, 2000)); //wait for a moment between 0 and 2 s
                }
                Console.WriteLine(Thread.CurrentThread.Name + " ended printing.");
            }
    
            static void Main(string[] args)
            {
                Thread[] threadArray = new Thread[threadCount];
                for (int ii = 0; ii < threadCount; ii++) //create, name and start threads
                {
                    threadArray[ii] = new Thread(new ThreadStart(PrintSomething));
                    threadArray[ii].Name = "Thread no " + ii.ToString();
                    threadArray[ii].Start();
                }
                foreach (Thread watek in threadArray) //wait for all threads
                {
                    watek.Join();
                }
                Console.WriteLine("That's all, press ENTER...");
                Console.ReadLine();
            }
        }
    Compile and run F5 (debug mode) or ctrl + F5 (release mode).

  3. Passing a parameter to a thread function (0,5 points) 
    In the above program, 10 threads were created to perform 10 iterations of the loop. The number of iterations is now hard-coded as a global variable. Create a new function DisplaySomethingPar, which can be passed via parameter the number of iterations to be performed by it. Use it to create 10 threads. 

  4. Threads and lambda notation (0,5 point)  
    Run 10 threads anonymously by passing the number of iterations in the parameter. Use lambda notation.

  5. Priority (1.5 points) 
    • Create two threads (threadH and threadL) and 16 threads in them, where we execute the Thread.SpinWait (1000000000) statement; (with slower computers this value can be reduced).
    • In H type threads, we set the property before start Priority = ThreadPriority.Highest
    • In threads of type LPriority = ThreadPriority.Lowest.
    • Start both threads.
    • Use Stopwatch to measure how many milliseconds it takes to execute H threads and L threads (H and L threads should run simultaneously). Which threads ran faster?
    • When the program is stable (we can wait for its end), you can set the priority of the process at the very beginning Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.RealTime;
    • Run and watch what happens

  6. Threads and lock (1 point)
    • Add a new project Synch to the existing solution.(choose from the context menu of solution Add->New Project)
    • Set a new project as default to run (select from the context menu of the project Set as StartUp Project)
       DotNet1En_04.png
    • Using the code from your first project, create 10 threads that follow the method below.
      static void PrintSomething()
          {
          Random rand = new Random(Thread.CurrentThread.ManagedThreadId);//init random by thread no 
          Thread.Sleep(rand.Next(0, 100));
          Console.WriteLine(Thread.CurrentThread.Name + " begin writeing:");
         
          for (int ii = 0;ii<liczbaIteracji;ii++)
      	{
      	Console.Write("Alice ");
              Thread.Sleep(rand.Next(0, 100));  //sleep on  0 to 0,1 s
              Console.Write("has ");
              Thread.Sleep(rand.Next(0, 100)); //sleep on  0 to 0,1 s
              Console.WriteLine("a cat " + ii);
              Thread.Sleep(rand.Next(0,2000));//sleep on 0 to 2s
      	}
          Console.WriteLine(Thread.CurrentThread.Name + " end writeing.");
          }
    • Compile and see how it works for several threads
    • Use lock so that any " Ala has a cat" text is displayed integrally, but you should this in that way the program will run as fast as possible without removing sleeps.
    • Note that the opening and closing inscription can also be interlaced with the display of the Ala has a cat. This also needs to be secured.
  7. Ending Threads (0,9 points.)
    • Add a new console project to the current solution and name it Ending . Use .net < 5.0 (not .core)
    • Use the following code to create and start a thread:
                  Thread thread = new Thread(() =>
                  {
                      Console.WriteLine("Wątek uruchomiony i idzie spać...");
                      try
                      {
                          Thread.Sleep(2000);
                      }
                      catch (ThreadInterruptedException tiex)
                      {
                          Console.WriteLine("I cought exception ThreadInterruptedException: " + tiex.Message);
                      }
                      catch (ThreadAbortException taex)
                      {
                          Console.WriteLine("I cought exception ThreadAbortException: " + taex.Message);
                      }
                      finally
                      {
                          Console.WriteLine("I'm doing finally");
                      }
                      Console.WriteLine("Thread finished in normal way");
                  });
                  thread.Start();
      
    • In the main thread, add a wait for a child thread and then interrupt the thread with Interrupt . Watch what is happening on the console.
    • Use Abort instead of Interrupt. Watch what is happening on the console.(but in .net 5.0 or .core this cause PlatformNotSupportedException)
    • Now before Abort add a 1 second sleepa and see the results again.
    • In the block that catches ThreadAbortException , apply ResetAbort and observe the differences.

  8. Thread states (0,5 points)
    Add printout of thread state to above program to get below states, check for Abort and Interrupt:
    • Unstarted
    • Unstarted, AbortRequested
    • Running
    • WaitSleepJoin
    • AbortRequested
    • Aborted
    • Stopped

  9. Report

        Don't forget the report