Streams in .NET. Part 1

    This topic gives initial information on the use of threads on the .NET platform. This is my first post on Habré, so do not judge very harshly. I would also like to hear constructive criticism about how you can improve the material.

    A thread is an independent sequence of instructions in a program. The easiest way to create threads is to invoke the delegate asynchronously.
    static int TestThread(int data, int ms)
       {
         Console.WriteLine("TestThread started");
         Thread.Sleep(ms);
         Console.WriteLine("TestThread completed");
         return ++data;
       }

    public delegate int TestThreadDelegate(int data, int ms);

    * This source code was highlighted with Source Code Highlighter.

    There are several ways to find out if a delegate has completed its work. This can be done using the BeginInvoke () method, in which the input parameters can be passed along with the delegate type. This method returns an IAsyncResult type that has the IsCompleted property. The second way to wait for a result is to use a wait descriptor. You can access it using the AsyncWaitHandle property. The third way is to use an asynchronous callback:
    static void Main()
       {

         TestThreadDelegate d1 = TestThread;

         d1.BeginInvoke(1, 3000, TestThreadCompleted, d1);
         for (int i = 0; i < 100; i++)
         {
          Console.Write(".");
          Thread.Sleep(50);
         }

        }

    static void TestThreadCompleted(IAsyncResult ar)
       {
         if (ar == null) throw new ArgumentNullException("ar");
         TestThreadDelegate d1 = ar.AsyncState as TestThreadDelegate;
         Trace.Assert(d1 != null, "Invalid object type");

         int result = d1.EndInvoke(ar);
         Console.WriteLine("result: {0}", result);
       }

    * This source code was highlighted with Source Code Highlighter.

    Another way to create threads is to use the Thread class. It also allows you to manage them.
    using System;
    using System.Threading;

    namespace Csharp.Threading.FirstThread
    {
      class Program
      {
       static void Main(string[] args)
       {
         Thread t1 = new Thread(ThreadMain);
         t1.Start();
         Console.WriteLine("This is the main thread.");
       }
       static void ThreadMain()
       {
         Console.WriteLine("In thread.");
       }
      }
    }

    * This source code was highlighted with Source Code Highlighter.

    There are two ways to transfer data to threads: using the Thread constructor with the ParameterizedThreadStart delegate, or by creating a special class and defining the thread method as an instance method:
    public class MyThread
      {
       private string data;

       public MyThread(string data)
       {
         this.data = data;
       }

       public void ThreadMain()
       {
         Console.WriteLine("Running in a thread, data: {0}", data);
       }
      }

    * This source code was highlighted with Source Code Highlighter.

    In Main:
      MyThread obj = new myThread(“text”);

      Thread tr = new Thread(obj.ThreadMain);

      tr.Start();

    * This source code was highlighted with Source Code Highlighter.

    There are two types of streams: priority and background. The process continues to run until at least one priority thread is running. Using the Thread class, it is created by default. For the stream to be background, use the IsBackground property.

    The operating system plans the execution order of the threads. This process can be influenced by assigning a thread the appropriate priority using the Priority property.

    Sometimes you need to create a set of threads in advance, and also increase or decrease this set when necessary. For this, the ThreadPool class is provided.
    using System;
    using System.Threading;

    namespace Csharp.Threading.Pools
    {

      class Program
      {
       static void Main()
       {

         for (int i = 0; i < 5; i++)
         {
          ThreadPool.QueueUserWorkItem(JobForAThread);

         }

         Thread.Sleep(5000);
       }

       static void JobForAThread(object state)
       {
         for (int i = 0; i < 3; i++)
         {
          Console.WriteLine("loop {0}, running inside pooled thread {1}", i,
            Thread.CurrentThread.ManagedThreadId);
          Thread.Sleep(10);     
         }

       }
      }
    }

    * This source code was highlighted with Source Code Highlighter.

    But thread pools have some limitations: they are background, and you cannot change the priority or name of a thread in the pool.

    That's all for a start. Next time we'll talk about deadlock and thread synchronization.

    UPD Ported to .NET. Thanks for the karma.

    Also popular now: