Asynchronous Delegation for multi-thread operations

Source: Internet
Author: User

When a freshman looks for a job, multithreading is a basic question that almost all companies will ask.

Here is a summary of multi-threaded operations, which summarizes the implementation of multi-threaded operations through asynchronous delegation.

Defining a delegate is the easiest way to create a thread and call it asynchronously. Delegation is a safe reference of the method type. At the same time, delegate the smart tooth asynchronous call method.

Delegates use the thread pool to complete asynchronous tasks.

When your program uses an asynchronous delegate, the delegate automatically creates tasks where the ige thread is executed. The delegate uses the thread pool to complete asynchronous tasks. All asynchronous delegate calls will call the threads in the system thread pool to complete asynchronous tasks.

In the following simple example, we define an asynchronous delegate and display the thread in which the function runs at each output.

In asynchronous delegation, three techniques can be used to asynchronously call the delegation. The following describes three methods to call asynchronous delegation.

1. vote to determine whether asynchronous delegation is complete

Call the BeginInvoke () method in the delegate and return the IAsyncResult result. The source code of the program is as follows:

[Csharp]
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using System. Threading;
 
Namespace AsyncDelegate
{
Class Program
{
Public delegate int TakeSomeTimeDelegate (int data, int MS );
 
Static void Main (string [] args)
{
TakeSomeTimeDelegate dl = TakeSomeTime;
IAsyncResult ar = dl. BeginInvoke (1,200, null, null );
 
While (! Ar. IsCompleted)
{
Console. WriteLine (".");
Console. WriteLine ("Run in thread:" + Thread. CurrentThread. ManagedThreadId );
Thread. Sleep (50 );
}
 
Int result = dl. EndInvoke (ar );
Console. WriteLine ("Result: {0}", result );
}
 
Static int TakeSomeTime (int data, int MS)
{
Console. WriteLine ("TakeSomeTime started! ");
Console. WriteLine ("Run in thread:" + Thread. CurrentThread. ManagedThreadId );
Thread. Sleep (MS );
Console. WriteLine ("TakeSomeTime Completed! ");
Return ++ data;
}
}
}
Output result of the program

 

We can see that the main thread and asynchronous delegate thread are executed simultaneously.

If the main thread is terminated without waiting for the delegation to complete other tasks before the delegation ends, the delegation thread will stop.

Int result = dl. EndInvoke (ar); The EndInvoke () function will always block the main thread before the asynchronous delegation is complete and the asynchronous delegation is completed. This function ensures that the asynchronous delegation can be completed correctly.

 

2. Wait until the asynchronous Delegate of the handle is determined.

Use the AsyncWatiHandle attribute to access the waiting handle. The WaitOne () method blocks the current thread until the asynchronous call thread finishes returning the available handle before executing the current thread.

Program:

[Html]
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using System. Threading;
 
Namespace AsyncDelegate
{
Class Program
{
Public delegate int TakeSomeTimeDelegate (int data, int MS );
 
Static void Main (string [] args)
{
TakeSomeTimeDelegate dl = TakeSomeTime;
IAsyncResult ar = dl. BeginInvoke (1,200, null, null );
 
While (true)
{
Console. WriteLine (".");
Console. WriteLine ("Run in thread:" + Thread. CurrentThread. ManagedThreadId );
If (ar. AsyncWaitHandle. WaitOne (100, false ))
{
Console. WriteLine ("Can get the result now ");
Break;
}
}
 
// While (! Ar. IsCompleted)
//{
// Console. WriteLine (".");
// Console. WriteLine ("Run in thread:" + Thread. CurrentThread. ManagedThreadId );
// Thread. Sleep (50 );
//}
 
Int result = dl. EndInvoke (ar );
Console. WriteLine ("Result: {0}", result );
}
 
Static int TakeSomeTime (int data, int MS)
{
Console. WriteLine ("TakeSomeTime started! ");
Console. WriteLine ("Run in thread:" + Thread. CurrentThread. ManagedThreadId );
Thread. Sleep (MS );
Console. WriteLine ("TakeSomeTime Completed! ");
Return ++ data;
}
}
}

Running result:

 

 

 

Ar. AsyncWaitHandle. WaitOne () blocks the current thread and executes the current thread again after the asynchronous call thread completes obtaining the available handle.

 

3. Use the asynchronous callback function to determine whether the asynchronous call thread ends.

 

The operations of callback functions are complex and difficult to understand and maintain programs. Therefore, in general, callback functions are not used without callback functions.

 

When using a callback function, you must note that this function is called from the delegate thread rather than from the main thread.

[Csharp]
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using System. Threading;
 
Namespace AsyncDelegate
{
Class Program
{
Public delegate int TakeSomeTimeDelegate (int data, int MS );
 
Static void Main (string [] args)
{
TakeSomeTimeDelegate dl = TakeSomeTime;
IAsyncResult ar = dl. BeginInvoke (1,200, TakeSomeTimeCompleted, dl );
For (int I = 0; I <10; I ++)
{
Console. WriteLine (".");
Console. WriteLine ("Run in thread:" + Thread. CurrentThread. ManagedThreadId );
Thread. Sleep (50 );
}
 
// Int result = dl. EndInvoke (ar );
// Console. WriteLine ("Result: {0}", result );
}
 
Static int TakeSomeTime (int data, int MS)
{
Console. WriteLine ("TakeSomeTime started! ");
Console. WriteLine ("Run in thread:" + Thread. CurrentThread. ManagedThreadId );
Thread. Sleep (MS );
Console. WriteLine ("TakeSomeTime Completed! ");
Return ++ data;
}
 
Static void TakeSomeTimeCompleted (IAsyncResult ar)
{
If (ar = null)
{
Throw new ArgumentNullException ("ar ");
}
TakeSomeTimeDelegate dl = ar. AsyncState as TakeSomeTimeDelegate;
Int result = dl. EndInvoke (ar );
Console. WriteLine ("result: {0}", result );
// Console. WriteLine ("Run in thread:" + Thread. CurrentThread. ManagedThreadId );
}
}
}

 

Running result:

Related Article

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.