C # multithreaded programming detailed _c# tutorial

Source: Internet
Author: User

C # provides a wealth of multithreaded operations, which is a great convenience for programming.

First, the use of threading reasons

1. You can use threads to isolate code from other code to improve the reliability of your application.

2. You can use threads to simplify coding.

3, you can use the thread to implement concurrent execution.

II. Basic Knowledge

1. Processes and Threads: processes as the basic unit of the Operating system execution program, with resources for the application, processes containing threads, process resources being shared by threads, threads not owning resources.

2, foreground thread and background thread: Create a new line through the thread class Cheng think foreground thread. When all foreground threads are closed, all background threads are also terminated directly, and no exceptions are thrown.

3, Suspend (Suspend) and Wake (Resume): Because the thread's execution sequence and the execution of the program is unpredictable, so the use of suspend and wake prone to deadlock, in practical applications should be as little as possible.

4, blocking thread: Join, blocking the calling thread until the thread terminates.

5, terminate the thread: Abort: Throw ThreadAbortException exception to let the thread terminate, the terminated thread is not awakened. Interrupt: Throws a Threadinterruptexception exception to terminate the thread and can continue execution by catching the exception.

6, Thread priority: AboveNormal BelowNormal highest Lowest normal, default to normal.

Third, the use of the thread

Thread functions are passed by delegates, either without parameters or with parameters (only one argument), and you can encapsulate parameters with a class or struct body.

Namespace Test
{
  class program
  {
    static void Main (string[] args)
    {
      thread t1 = new Thread (new ThreadStart (TestMethod));
      Thread t2 = new Thread (new Parameterizedthreadstart (TestMethod));
      T1. IsBackground = true;
      T2. IsBackground = true;
      T1. Start ();
      T2. Start ("Hello");
      Console.readkey ();
    }

    public static void TestMethod ()
    {
      Console.WriteLine ("Thread function with no parameters");
    }

    public static void TestMethod (object data)
    {
      string datastr = data As String;
      Console.WriteLine ("Thread function with parameters, parameter: {0}", Datastr);}} 


Four, thread pool

Because of the cost of creating and destroying threads, excessive use of threads can lead to waste of memory resources, and the concept of thread pools is introduced for performance reasons. The thread pool maintains a request queue, the code of the thread pool extracts the task from the queue, and then it is delegated to one of the thread pool's threads for execution, and the thread is not immediately destroyed so that it can perform tasks in the background and reduce the overhead of thread creation and destruction.

Thread pool line Cheng is considered a background thread (IsBackground).

Namespace Test
{
  class
  program {
    static void Main (string[] args)
    {
      //Add work items to the thread pool queue. Here you can pass a thread parameter
      threadpool.queueuserworkitem (TestMethod, "Hello");
      Console.readkey ();
    }

    public static void TestMethod (object data)
    {
      string datastr = data As String;
      Console.WriteLine (DATASTR);}}


V. Task class

It is simple to initiate an asynchronous thread execution using the ThreadPool QueueUserWorkItem () method, but the biggest problem with this approach is that there is no built-in mechanism to let you know when the operation is done, and whether there is a built-in mechanism to get a return value after the operation completes. To do this, you can use the task class in System.Threading.Tasks.

Constructs a Task<tresult> object and passes the return type of an action for the generic TResult parameter.

Namespace Test
{
  class program
  {
    static void Main (string[] args)
    {
      task<int32> t = new Task<int32> (n => Sum ((Int32) n), 1000);
      T.start ();
      T.wait ();
      Console.WriteLine (T.result);
      Console.readkey ();
    }

    private static Int32 sum (Int32 N)
    {
      Int32 sum = 0;
      for (; n > 0;--n)
        checked{sum = n;}//Result too large, throw exception return
      sum;
    }
  }


When a task completes, a new task is started automatically.

Once a task completes, it can start another task, overwriting the preceding code and not blocking any threads.

Namespace Test
{
  class program
  {
    static void Main (string[] args)
    {
      task<int32> t = new Task<int32> (n => Sum ((Int32) n), 1000);
      T.start ();
      T.wait ();
      Task cwt = t.continuewith (Task => Console.WriteLine ("The result is {0}", T.result));
      Console.readkey ();
    }

    private static Int32 sum (Int32 N)
    {
      Int32 sum = 0;
      for (; n > 0;--n)
        checked{sum = n;}//result overflow, throw exception return
      sum;
    }
  }


Vi. delegate Asynchronous execution

Asynchronous invocations of Delegates: BeginInvoke () and EndInvoke ()

Namespace Test
{public
  delegate string MyDelegate (object data);
  Class program
  {
    static void Main (string[] args)
    {
      MyDelegate mydelegate = new MyDelegate (TestMethod); C8/>iasyncresult result = MyDelegate. BeginInvoke ("Thread Param", Testcallback, "Callback Param");

      Asynchronous execution completes
      string resultstr = MyDelegate. EndInvoke (result);
    }

    Thread function public
    static string TestMethod (object data)
    {
      string datastr = data As String;
      return datastr;
    }

    The asynchronous callback function public
    static void Testcallback (IAsyncResult data)
    {
      Console.WriteLine (data). asyncstate);}}


Seven, thread synchronization

1 atomic operation (interlocked): All methods perform an atomic read or write operation once.

2 lock () statement: Avoid locking the public type, otherwise the instance will go beyond the scope of code control and define a private object to lock.

3 Monitor realizes thread synchronization

The acquisition and release of exclusive locks is achieved through Monitor.Enter () and Monitor.Exit (), after which exclusive resources are obtained and no other threads are allowed to access them.

There is also a TryEnter method that does not block waiting when a resource is not requested, and can set the timeout time to get no direct return false.

4) ReaderWriterLock

When you read and write less on resource operations, in order to improve resource utilization, so that read operations are locked as shared locks, multiple threads can read resources concurrently, while write operations are exclusive locks, allowing only one thread to operate.

5 The event class implements synchronization

The event class has two states, a termination state and a WaitOne state, which can be invoked successfully when the state is terminated, and the time state is set to the signaled state through the set.

①autoresetevent (auto reset event)

②manualresetevent (Manual reset event)

6) Signal Quantity (semaphore)

The semaphore is an int variable maintained by the kernel object, at 0 o'clock, the thread is blocked, greater than 0 o'clock unblocked, and when a waiting thread on a semaphore is unblocked, the semaphore counts +1.

The thread will reduce the semaphore by 1 by WaitOne, and the signal will be added 1 through release, which is simple to use.

7 Mutex (mutex)

Exclusive resources, similar in usage to semaphore.

8. Cross-process synchronization

System-level synchronization can be achieved by setting the name of the synchronization object, and different applications identify different synchronization objects by synchronizing the names of the objects.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.