Talk about C # multithreading things-thread synchronization and thread priority

Source: Internet
Author: User
Tags net thread semaphore

The previous article shared some basic knowledge of multithreading, and today we continue to learn.

Study hard and become the best of yourself.

First, the Task class

Last time we talked about the thread pool, the QueueUserWorkItem () method of the thread pool initiates an asynchronous thread execution is simple

But the biggest problem with this approach is that there is no built-in mechanism to let you know when the operation is complete, and there is no built-in mechanism to get a return value after the operation is complete. To do this, you can use the task class in System.Threading.Tasks.

Simple Code implementation:

usingSystem;usingSystem.Threading.Tasks;namespacethreading{classProgram { Public StaticInt32 Threadsum (Int32 n) {Int32 sum=0;  for(; n >0; --N) Sum+=N; returnsum; }        Static voidMain (string[] args) {            vart =NewTask<int32> (n = threadsum ((Int32) n), -);            T.start (); varCWT = T.continuewith (Task = Console.WriteLine ("The result is {0}", T.result));        Console.readkey (); }    }}
sample code for the task classSecond, asynchronous execution

Asynchronous execution code for delegates: BeginInvoke () and EndInvoke ()

usingSystem;namespacethreading{ Public Delegate stringMyDelegate (Objectdata); classProgram { Public Static stringThread1 (Objectdata) {            returndata.        ToString (); }         Public Static voidthreadcallback (IAsyncResult data) {Console.WriteLine ("Threadcallback = >"+data.        asyncstate); }        Static voidMain (string[] args) {            varMyDelegate =Newmydelegate (THREAD1); IAsyncResult result= MyDelegate. BeginInvoke ("Thread1 Para", Threadcallback,"Callback Para"); //Asynchronous execution Complete            varResultStr =MyDelegate.            EndInvoke (result);            Console.WriteLine (RESULTSTR);        Console.readkey (); }    }}
delegate asynchronous execution sample codeThird, thread synchronization

1. Mutex lock () statement

The preferred technique for synchronizing access to shared resources is the lock keyword for C #, which allows you to define a code statement for a thread synchronization, which requires defining a tag (that is, an object reference), which must be obtained when the thread enters the lock range, and the lock needs to be released when the lock range is exited. When trying to lock a private method at an instance level, use the reference to the object where the method itself is located. However, if you need to lock a piece of code in a public member, it is safer to declare the private object member as the lock identifier.

 Public class democlass{    privatereadonlyobjectnewobject();      Public void Method ()    {        //  use lock identification        Lock (Threadlock)        {            //...         }    }}

2. Monitor realizes thread synchronization

by Monitor.Enter () and Monitor.Exit (), the acquisition and release of the exclusive lock is achieved, and the other threads are not allowed to access the resource.

There is also a TryEnter method that does not block the wait when the resource is requested, can set the time-out period, and cannot get the direct return false.

 public  class   democlass{ readonly  object  threadlock = new  object      ();  public  void   Method () {monitor.enter (threadlock);  try   { //     {monitor.exit (threadlock); }    }}

3, Maintenance free lock (System.Threading.Interlocked) to achieve thread synchronization, interlocked allows us to do some atomic operation of the data: CompareExchange (), decrement (), Exchange ( ), Increment (). These static methods need to pass in the variable in a reference way. For example: Note that both newval and intval values are incremented.

4. The [synchronization] attribute can effectively keep the members of an instance of an object in a thread-safe manner. When the CLR allocates an object with a [synchronization] attribute, it places the object in the synchronization context. This is a lazy way to write thread-safe code because it does not require us to actually drill down into the details of the sensitive data, but this approach has an impact on performance, because even if a method does not use a shared resource, the CLR will still lock the call to that method.

5. System built-in objects

Mutex (mutex), Semaphore (Semaphore), event (autoresetevent/manualresetevent), thread pool

Four, Thread priority

The system assigns a priority level to each thread. NET thread priority, which specifies the relative priority of a thread relative to other threads, which prescribes the order in which threads are executed, the priority level defaults to normal for threads created in the CLR, while threads created outside the CLR retain their previous precedence when they enter the CLR. You can get or set the priority level of a thread by accessing the thread's Precedence property.

The ThreadPriority enumeration in the System.Threading namespace defines all the possible values for a set of thread priorities, which I've used to rank from high to low, and the specific instructions are not explained here.

Highest, AboveNormal, Normal, BelowNormal, Lowest

In addition to these there are realtime, but realtime priority to avoid, his priority is very high, and even interfere with the operating system tasks, such as blocking some necessary disk I/O and network transmission. It may also cause the keyboard and mouse input not to be processed in time, causing the user to feel the crash.

code example:

usingSystem;usingSystem.Threading;namespacethreading{classProgram { Public Static voidThread1 () { for(inti =0; I <Ten; i++) {Console.Write ("1"); }        }         Public Static voidThread2 () { for(inti =0; I <Ten; i++) {Console.Write ("2"); }        }         Public Static voidThread3 () { for(inti =0; I <Ten; i++) {Console.Write ("3"); }        }         Public Static voidThread4 () { for(inti =0; I <Ten; i++) {Console.Write ("4"); }        }         Public Static voidThread5 () { for(inti =0; I <Ten; i++) {Console.Write ("5"); }        }        Static voidMain (string[] args) {            varT1 =NewThread (THREAD1); vart2 =NewThread (THREAD2); varT3 =NewThread (THREAD3); varT4 =NewThread (THREAD4); varT5 =NewThread (THREAD5); T1. Priority=threadpriority.highest; T2. Priority=Threadpriority.abovenormal; T3. Priority=Threadpriority.normal; T4. Priority=Threadpriority.belownormal; T5. Priority=threadpriority.lowest; T1.            Start (); T2.            Start (); T3.            Start (); T4.            Start (); T5.            Start ();        Console.readkey (); }    }}

Operation Result:

It is obvious that the priority of the thread is executed according to the order of precedence.

V. Blocking the calling thread

Join blocks the calling thread until the thread terminates.

usingSystem;usingSystem.Threading;namespacethreading{classProgram {Static voidMain (string[] args) {            varThreadstarta =NewThreadStart (Delegate()            {                  for(inti =0; I <1000000; i++)                {                    ifI10000==0) Console.Write ("A");            }            }); varThreada =NewThread (Threadstarta); varTHREADSTARTB =NewThreadStart (Delegate()            {                   for(inti =0; I <500000; i++)                {                    ifI10000==0) Console.Write ("B");  } threada.join (); //blocking thread threadb, inserting Threada for execution                 for(inti =0; I <500000; i++)                {                    ifI10000==0) Console.Write ("B1");            }            }); varTHREADB =NewThread (THREADSTARTB); //Start ThreadThreada.start ();            Threadb.start ();        Console.readkey (); }    }}

Operation Result:

From the results of the operation can be seen: At the beginning, Threada and threadb alternating execution, when threadb execution to the Threada.join () method, Threadb is blocked, Threada inserted in separate execution, when the Threada executed, THREADB continues to execute.

In addition to Threada and THREADB, there is also a main thread (main thread) in the program. Now let's add some output code to the main thread to see how the main thread and worker A and B are running concurrently.

Vi. attention of Canada

If this article is helpful to you, please click on " good text to top " and " Follow me " in the bottom right corner.

Talk about C # multithreading things-thread synchronization and thread priority

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.