Multi-Threaded Notes

Source: Internet
Author: User

Parameterizedthreadstart and ThreadStart are like, the main difference is that the Parameterizedthreadstart delegate is a method with parameters, the parameter value can be a value pair image, or it can be a custom pair image.

Thread.Start () starts the line Cheng considers the foreground thread. The system will wait for all foreground threads to finish running and the application domain will not be uninstalled automatically.

 Public classpersoninfo{ Public stringname{Get;Set;} Public intage{Get;Set;} Public stringaddress{Get;Set;}}Static voidShowMessage (Objectobj) {PersonInfo pinfo=obj asPersonInfo; Console.WriteLine ("Name:"+pinfo.name); Console.WriteLine ("Age :"+pinfo.age); Console.WriteLine ("Address:"+pinfo.address);}
Thread Thread=NewThread (NewParameterizedthreadstart (showmessage)); PersonInfo pinfo=NewPersonInfo ();p info.name="Zjh";p info.age=" -";p info.address="Zhe Jiang"thread. Start (pinfo);

thread Termination: You can use the Abort () method to throw an exception threadabortexception after execution. To recover a thread before terminating the thread, you can try{}catch after catching the exception ( ThreadAbortException ex) {thread. ResetAbort ();} Call the ResetAbort () method to recover. Use Thread. Join () guarantees that the application domain waits for the thread to end before terminating the run.

Thread pool: Thradpool.getmax (out int workthreads,out int completionportthreads) and threadpool.setmax (int workthreads,int completionPortThreads) Two methods read and set the maximum number of threads in the CLR thread pool for worker threads and I/O threads. Gets the number of threads in the thread pool that are working can use the method Threadpool.getavailablethreads (out int workthreads,out int completionportthreads). The engineer thread has two modes of operation: 1, using the ThreadPool.QueueUserWorkItem () method, 2, using the delegate.

ThreadPool has two ways to start a worker thread directly: ThreadPool.QueueUserWorkItem (WaitCallback), ThreadPool.QueueUserWorkItem (WaitCallback , object), WaitCallback a non-return value method that points to an object parameter.

Static void AsyncCallback (object  obj) {     thread.sleep (Console.WriteLine)       ( " obj: "+obj);} ThreadPool.QueueUserWorkItem (new  WaitCallback (AsyncCallback)); ThreadPool.QueueUserWorkItem (new WaitCallback (AsyncCallback),"test" );

Delegate class: A thread in the CRL thread pool, the most flexible and most commonly used method is to use the delegate's Async method.

Delegate voidMyDelegate (stringa); Public voidShowMessage (stringa) {Console.WriteLine (a);} MyDelegate delegate1=Newmydelegate (showmessage);d Eletage1 ("Test");varmethods=delegate1. GetType (). GetMethods ();if(methods!=NULL){    foreach(MethodInfo Iteminchmethods) {Console.WriteLine ("MethodName:"+item. Name");    }}
 Public classMydelegate:multicastdelegate { PublicMyDelegate (ObjectTargetintmethodptr); //invoking a Delegate method         Public Virtual voidInvoke (); //Asynchronous Delegate         Public VirtualIAsyncResult BeginInvoke (AsyncCallback callback,ObjectState );  Public Virtual voidEndInvoke (IAsyncResult result); }
Call the Invoke () method, and all methods corresponding to this delegate will execute. BeginInvoke and EndInvoke support the asynchronous invocation of the delegate method, BeginInvoke the thread that is enabled is the property of the worker thread in the CRL thread pool.
Iasynceresult BeginInvoke ("Test", AsyncCallback callback,object State), except for the last two arguments, the other parameters are the parameters of the delegate method, Returns the IasyncResult of an interface, and then calls the EndInvoke (IasyncResult) method to end the asynchronous operation and obtain the result of the delegate.

IAsyncResult
 Public Interface iasyncresult{    object asyncstate {get;}            // gets a user-defined object that qualifies or contains information about an asynchronous operation.     wailhandle asyncwaithandle {get;}   // gets the WaitHandle that is used to wait for the asynchronous operation to complete.     bool completedsynchronously {get;}  // gets an indication of whether the asynchronous operation completed synchronously.     bool iscompleted {get;}             // gets an indication whether the asynchronous operation has completed. }

Determine if the drag is complete and can be used

 while(!result. iscompleted) {//executes the main thread. }stringresult=EndInvoke (result);//wait 200 milliseconds if the delegate does not execute the end while(!result. Asyncwaithandle.waitone ( $)){     //executes the main thread. }//If you have more than one delegate, you can use WaitHandle, which has two methods: WaitAny (Waithandler[],int), Wainall (waithandler[],int);mydelegate D1=NewMyDelegate (ShowMessage)
MyDelegate D2=NewMyDelegate (ShowMessage)
IAsyncResult RESULT1= D1. BeginInvoke ("Test",NULL,NULL);
IAsyncResult result2= D2. BeginInvoke ("test1",NULL,NULL);
Waithandle[] Waits=NewWAITHANDLE[]{RESULT1. Asyncwaithandle,result2. AsyncWaitHandle};
while(! WaitHandle.WaitAll (Waits, $){ //executes the main thread. }

Using polling to detect the completion of an async method is cumbersome and inefficient, and can be resolved using the callback function of the Async method.

Delegate stringMyDelegate (stringitem);Static voidcomplated (IAsyncResult result) {stringobj =result. Asyncstate.tostring ();//AsyncResult result2= Result asAsyncResult; MyDelegate delegate1=result2.  AsyncDelegate; stringData=delegate1. EndInvoke (RESULT2)}Static stringTestdelegate (stringItem) {returnDateTime.Now.Tostring ("YYYY-MM-DD")+item;} MyDelegate delegate1=Newmydelegate (testdelegate);d elegate1. BeginInvoke (delegate1,complated,"Test");



Multi-Threaded Notes

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.