C # thread waits (blocked)

Source: Internet
Author: User

Here I would like to emphasize a concept,

Multithreading is multi-threading,

Asynchronous programming is asynchronous programming

These two are the concepts of distinction;

I can say that multithreading is inherently asynchronous, but you can't say that multithreading is equivalent to our asynchronous programming;

The root cannot say that asynchronous programming is our multithreading. Don't confuse it here;

The evolution in re-NET is as follows:

Multithreading: Thread =>threadpool=> Task

Asynchronous Programming: Bengininvokexxx endinvokexxx iasyncresult=> Async await (this is used in conjunction with Task).

OK next, to summarize the wait for our thread (Task).

Summarize:

Method One: Thread.Sleep (), this to estimate that the waiting time should be greater than the time our child thread executes.

Method Two: Of course is our most commonly used join () method, blocking the current method of calling the Chengcheng, until our sub-thread execution is complete.

Method Two: Main thread rotation sub-thread (this is based on our IAsyncResult programming mode, in time the legendary beginxxxx endxxxx this mode)

Method Three: The method of using the notification is our EEVNTWAITHANLD = new Autoresteevnt (false), and then WaitOne and Set the way to proceed, the effect is very good drop ah;

Method Four: I named it as a folk prescription: is the use of exclusive locking mechanism, when the child thread after the lock, release, to our main thread, the premise is to ensure that our child thread first get lock;

Method Five: This is the wait method based on our task;

Here I give some, practice demo, only for reference use;

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading;usingSystem.Threading.Tasks;namespaceconsoleapplication13{//we call it waiting for a child thread, or waiting for a child thread for a certain amount of time;//The most primitive is the method of using waiteevnt; we can even use the poll way;//and the callback mode based on event programming;         Public classPerson {}classProgram {//evnet wait handle//This method can also be used for thread synchronization.         Public Static ObjectLocker =New Object();  Public StaticEventWaitHandle handler =NewAutoResetEvent (false);  Public Static voidEat () {Thread.Sleep ( the); }         Public Static voidEat_withset () {Thread.Sleep ( the); Handler. Set (); //a sub-thread sends a signal to be done;        }         Public Static voidEat_withlock () {Console.WriteLine ("Shackles begin"); Lock(Locker) {Thread.Sleep ( the);//Suppose we have a lot of things to do here;//The effect is very good;} Console.WriteLine ("Shackle Release"); }         Public Static voidEat_loop () { for(inti =0; I <Ten; i++) {Thread.Sleep ( +); Console.WriteLine ("Child"); }        }        //then this method can't be empty.         Public Static  voideat_wait () { for(inti =0; I <Ten; i++) {Task.delay ( +).                Wait (); Console.WriteLine ("Child"); }        }         Public Static voidTestjoin () {Console.WriteLine ("Main start"); Thread Thread=NewThread (Eat); Thread.            Start (); //wait for me.Console.WriteLine ("The main thread does something else first;"); //This we can directly use the thread to bring the method;thread.            Join (); Console.WriteLine ("OK, the sub-threading is done ."); Console.WriteLine ("Main End");        Console.ReadLine (); }         Public Static voidTest_set () {Console.WriteLine ("Main start"); Thread Thread=NewThread (Eat_withset); Thread.            Start (); //wait for me.Console.WriteLine ("The main thread does something else first;"); Handler.            WaitOne (); Console.WriteLine ("OK, the sub-threading is done ."); Console.WriteLine ("Main End");        Console.ReadLine (); }         Public Static voidTest11 () {Console.WriteLine ("Main start"); Thread Thread=NewThread (Eat_withset); Thread.            Start (); //wait for me.Console.WriteLine ("The main thread does something else first;"); Handler. WaitOne (Timespan.fromseconds (3)); //note here, a little waitone and task.wait if both specify the waiting time;//If the child thread does not finish the time within the specified time, then we begin the method of the main thread;//There is no real cancellation thread here;//The problem comes again, if you want to cancel the sub-thread;Console.WriteLine ("Okay, no clogging, the main thread is gone,"); Console.WriteLine ("Main End");        Console.ReadLine (); }        //Folk prescription         Public Static voidTest_lock () {Console.WriteLine ("Main start"); Thread Thread=NewThread (Eat_withlock); Thread.            Start (); //wait for me.Console.WriteLine ("The main thread does something else first;"); //if it is single-layer, I still use a little folk prescription;//that is our lock method drops ah;Thread.Sleep ( -);//in order for the child thread to get the lock, we're estimating sleep here.//so it is called folk prescription;            Lock(locker) {//Of course this way, is completely out of a four-level state;//wait for another thread to release the lock;Console.WriteLine ("This means that one of our other threads has finished executing;");        } console.readline (); }        //If you want to cancel the original method, but also get the original method to operate, the whole is a troublesome thing;//But there is more convenience in our task;         Public Static voidTest_task () {//The cancellation of task is relatively simple;Console.WriteLine ("Main start"); Task Task= Task.run (() =eat_wait ()); Console.WriteLine ("Mian do something.then wait task"); //task.  Wait (); //By default, it waits for the task to finish executing;task. Wait (Timespan.fromseconds (3));//here can only wait three seconds, three seconds only, do not block our main thread;//Here's the thing to note is that waiting does not equal cancellation oh;//this point is relatively critical;//Let's start with a little bit of thread cancellation .Console.WriteLine ("Task completed ..."); Console.WriteLine ("Main End");        Console.ReadLine (); }           Static voidMain (string[] args) {            //Test (); //Test1 (); //Test11 (); //Test_lock (); //Test_task ();        }    }}

Here I am going to show you a set, to notify instances of multiple threads, or to understand that a broadcast is the same as passing messages;

Or: Multiple threads are waiting for a signal from a thread;

C # thread waits (blocked)

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.