Latest web development tutorials

C # Multithreading

Thread is defined as the execution path of the program.Each thread defines a unique flow of control. If your application involves complex and time-consuming operation, set different execution paths is often useful thread, each thread performs a specific job.

Threads arelightweight processes.A common example is the use of threads in parallel programming of modern operating system implementation. Use threads saving waste CPU cycles, while improving the efficiency of the application.

So far we have prepared a program is a single process to run as a single-threaded application instance is running. However, with such an application can only perform one task at the same time. In order to perform multiple tasks simultaneously, it can be divided into smaller thread.

Thread Life Cycle

Thread life cycle begins System.Threading.Thread class object is created, the end is terminated or completed in the execution thread.

The following lists the status of the thread lifecycle:

  • The state does not start: When a thread instance is created, but the method is not called Start condition.
  • Ready state: ready to run when the thread is waiting for CPU cycles and conditions.
  • Non-operating state: The following situations are not run under the thread:

    • The method has been called Sleep
    • The method has been called Wait
    • By I / O operations obstruction
  • Death Status: When the thread has completed execution or aborted status when.

Main thread

In C#, System.Threading.Thread class for thread work.It allows you to create and access a multithreaded application in a single thread. The first thread in the process to be executedis called the primary thread.

When a C # program begins execution, the main thread is automatically created. Use theThread class to create a thread is called the main thread child thread.You can use the Thread classCurrentThread property access thread.

The following program demonstrates the execution of the main thread:

using System;
using System.Threading;

namespace MultithreadingApplication
{
    class MainThreadProgram
    {
        static void Main (string [] args)
        {
            Thread th = Thread.CurrentThread;
            th.Name = "MainThread";
            Console.WriteLine ( "This is {0}", th.Name);
            Console.ReadKey ();
        }
    }
}

When the above code is compiled and executed, it produces the following results:

This is MainThread

Thread class common attributes and methods

The following table lists theThread class some common attributes:

属性描述
CurrentContext获取线程正在其中执行的当前上下文。
CurrentCulture获取或设置当前线程的区域性。
CurrentPrinciple获取或设置线程的当前负责人(对基于角色的安全性而言)。
CurrentThread获取当前正在运行的线程。
CurrentUICulture获取或设置资源管理器使用的当前区域性以便在运行时查找区域性特定的资源。
ExecutionContext获取一个 ExecutionContext 对象,该对象包含有关当前线程的各种上下文的信息。
IsAlive获取一个值,该值指示当前线程的执行状态。
IsBackground获取或设置一个值,该值指示某个线程是否为后台线程。
IsThreadPoolThread获取一个值,该值指示线程是否属于托管线程池。
ManagedThreadId获取当前托管线程的唯一标识符。
Name获取或设置线程的名称。
Priority获取或设置一个值,该值指示线程的调度优先级。
ThreadState获取一个值,该值包含当前线程的状态。

The following table lists theThread class some commonly used methods:

序号方法名 & 描述
1public void Abort()
在调用此方法的线程上引发 ThreadAbortException,以开始终止此线程的过程。调用此方法通常会终止线程。
2public static LocalDataStoreSlot AllocateDataSlot()
在所有的线程上分配未命名的数据槽。为了获得更好的性能,请改用以 ThreadStaticAttribute 属性标记的字段。
3public static LocalDataStoreSlot AllocateNamedDataSlot( string name)
在所有线程上分配已命名的数据槽。为了获得更好的性能,请改用以 ThreadStaticAttribute 属性标记的字段。
4public static void BeginCriticalRegion()
通知主机执行将要进入一个代码区域,在该代码区域内线程中止或未经处理的异常的影响可能会危害应用程序域中的其他任务。
5public static void BeginThreadAffinity()
通知主机托管代码将要执行依赖于当前物理操作系统线程的标识的指令。
6public static void EndCriticalRegion()
通知主机执行将要进入一个代码区域,在该代码区域内线程中止或未经处理的异常仅影响当前任务。
7public static void EndThreadAffinity()
通知主机托管代码已执行完依赖于当前物理操作系统线程的标识的指令。
8public static void FreeNamedDataSlot(string name)
为进程中的所有线程消除名称与槽之间的关联。为了获得更好的性能,请改用以 ThreadStaticAttribute 属性标记的字段。
9public static Object GetData( LocalDataStoreSlot slot )
在当前线程的当前域中从当前线程上指定的槽中检索值。为了获得更好的性能,请改用以 ThreadStaticAttribute 属性标记的字段。
10public static AppDomain GetDomain()
返回当前线程正在其中运行的当前域。
11public static AppDomain GetDomainID()
返回唯一的应用程序域标识符。
12public static LocalDataStoreSlot GetNamedDataSlot( string name )
查找已命名的数据槽。为了获得更好的性能,请改用以 ThreadStaticAttribute 属性标记的字段。
13public void Interrupt()
中断处于 WaitSleepJoin 线程状态的线程。
14public void Join()
在继续执行标准的 COM 和 SendMessage 消息泵处理期间,阻塞调用线程,直到某个线程终止为止。此方法有不同的重载形式。
15public static void MemoryBarrier()
按如下方式同步内存存取:执行当前线程的处理器在对指令重新排序时,不能采用先执行 MemoryBarrier 调用之后的内存存取,再执行 MemoryBarrier 调用之前的内存存取的方式。
16public static void ResetAbort()
取消为当前线程请求的 Abort。
17public static void SetData( LocalDataStoreSlot slot, Object data )
在当前正在运行的线程上为此线程的当前域在指定槽中设置数据。为了获得更好的性能,请改用以 ThreadStaticAttribute 属性标记的字段。
18public void Start()
开始一个线程。
19public static void Sleep( int millisecondsTimeout )
让线程暂停一段时间。
20public static void SpinWait( int iterations )
导致线程等待由 iterations 参数定义的时间量。
21public static byte VolatileRead( ref byte address )
public static double VolatileRead( ref double address )
public static int VolatileRead( ref int address )
public static Object VolatileRead( ref Object address )

读取字段值。无论处理器的数目或处理器缓存的状态如何,该值都是由计算机的任何处理器写入的最新值。此方法有不同的重载形式。这里只给出了一些形式。
22public static void VolatileWrite( ref byte address, byte value )
public static void VolatileWrite( ref double address, double value )
public static void VolatileWrite( ref int address, int value )
public static void VolatileWrite( ref Object address, Object value )

立即向字段写入一个值,以使该值对计算机中的所有处理器都可见。此方法有不同的重载形式。这里只给出了一些形式。
23public static bool Yield()
导致调用线程执行准备好在当前处理器上运行的另一个线程。由操作系统选择要执行的线程。

Create a thread

A thread is created by extending the Thread class. Executive Extended Thread class calls theStart () method to start the child threads.

The following program illustrates this concept:

using System;
using System.Threading;

namespace MultithreadingApplication
{
    class ThreadCreationProgram
    {
        public static void CallToChildThread ()
        {
            Console.WriteLine ( "Child thread starts");
        }
        
        static void Main (string [] args)
        {
            ThreadStart childref = new ThreadStart (CallToChildThread);
            Console.WriteLine ( "In Main: Creating the Child thread");
            Thread childThread = new Thread (childref);
            childThread.Start ();
            Console.ReadKey ();
        }
    }
}

When the above code is compiled and executed, it produces the following results:

In Main: Creating the Child thread
Child thread starts

Managing Thread

Thread Thread class provides a variety of management methods.

The following example demonstrates the use ofsleep () method is used in a specific time-out thread.

using System;
using System.Threading;

namespace MultithreadingApplication
{
    class ThreadCreationProgram
    {
        public static void CallToChildThread ()
        {
            Console.WriteLine ( "Child thread starts");
            // Thread is suspended to 5000 milliseconds int sleepfor = 5000; 
            Console.WriteLine ( "Child Thread Paused for {0} seconds", 
                              sleepfor / 1000);
            Thread.Sleep (sleepfor);
            Console.WriteLine ( "Child thread resumes");
        }
        
        static void Main (string [] args)
        {
            ThreadStart childref = new ThreadStart (CallToChildThread);
            Console.WriteLine ( "In Main: Creating the Child thread");
            Thread childThread = new Thread (childref);
            childThread.Start ();
            Console.ReadKey ();
        }
    }
}

When the above code is compiled and executed, it produces the following results:

In Main: Creating the Child thread
Child thread starts
Child Thread Paused for 5 seconds
Child thread resumes

Destroys threads

Abort () method is used to destroy threads.

By throwingthreadabortexception abort threads at runtime.This exception can not be caught, iffinallyblock, control will be sentfinallyblock.

The following program illustrates this point:

using System;
using System.Threading;

namespace MultithreadingApplication
{
    class ThreadCreationProgram
    {
        public static void CallToChildThread ()
        {
            try
            {

                Console.WriteLine ( "Child thread starts");
                // Count to 10
                for (int counter = 0; counter <= 10; counter ++)
                {
                    Thread.Sleep (500);
                    Console.WriteLine (counter);
                }
                Console.WriteLine ( "Child Thread Completed");

            }
            catch (ThreadAbortException e)
            {
                Console.WriteLine ( "Thread Abort Exception");
            }
            finally
            {
                Console.WriteLine ( "Could not catch the Thread Exception");
            }

        }
        
        static void Main (string [] args)
        {
            ThreadStart childref = new ThreadStart (CallToChildThread);
            Console.WriteLine ( "In Main: Creating the Child thread");
            Thread childThread = new Thread (childref);
            childThread.Start ();
            // Stop the main thread for some time Thread.Sleep (2000);
            // Now suspended child thread Console.WriteLine ( "In Main: Aborting the Child thread");
            childThread.Abort ();
            Console.ReadKey ();
        }
    }
}

When the above code is compiled and executed, it produces the following results:

In Main: Creating the Child thread
Child thread starts
0
1
2
In Main: Aborting the Child thread
Thread Abort Exception
Could not catch the Thread Exception