Asynchronous delegated learning notes

Source: Internet
Author: User

Asynchronous delegation is to define a method and open a new thread for this method to be executed in the background.

Defining a delegate and calling it asynchronously is a simple method for creating a thread.

Delegation is a secure reference of the method type. The delegate class supports asynchronous calling. In the background, the delegate class creates a thread for task execution.

We first define a method that takes some time to complete: takesawhile (INT data, int MS), this method calls thread. the sleep method can be executed only after the input parameter is milliseconds.

Code
    1. Public Static IntTakesawhile (IntData,IntMS)
    2. {
    3. Console. Writeline ("Takesawhile started");
    4. Thread. Sleep (MS );
    5. Console. Writeline ("\ Ntakesawhile complated");
    6. Return++ Data;
    7. }

Then define a delegate takesawhiledelegate () with the same parameters and return types, as shown below:

Code
    1. Public Delegate Int Takesawhiledelegate(IntData,IntMS );

Then we can use different technologies to asynchronously call the delegate and return results.

I. Repeated inquiries

After the method is handed over to the backend for execution, we can still check the execution status of the Delegate, as shown below ).

The created delegate class provides the begininvoke () method. In this method, you can pass the input parameters defined by the delegate type. The return type is iasyncresult. You can obtain information about the delegate through the returned result. The iscomplated method is used to check whether the delegate is completed.ProgramAlways execute:

 

Code
  1. Static VoidMain (String[] ARGs)
  2. {
  3. TakesawhiledelegateT1 = takesawhile;
  4. // Submit the task to the background for execution
  5. IasyncresultAR = t1.begininvoke (1, 9000,Null,Null);
  6. // Wait until the background thread ends
  7. While(! Ar. iscompleted)
  8. {
  9. Console. Write (".");
  10. Thread. Sleep (50 );
  11. }
  12. IntResult = t1.endinvoke (AR );
  13. // Obtain the returned results
  14. Console. Writeline ("Result: {0 }", Result );
  15. Console. Readline ();
  16. }

When the program is running, the delegate thread and the main thread run simultaneously. After the delegate thread is completed, the cycle of the main thread stops. You can also call the endinvoke method in the main thread to end the background thread.

If the background thread is not completed, the endinvoke method will wait until the background thread is completed or the main thread ends.

2. Wait for a while before asking

Another way to wait for the result of asynchronous delegation is to use the wait handle associated with iasyncreault. You can use the asyncwaithandle attribute to access the waiting handle. This property returns a waithandle type object, which can wait for the delegate thread to complete its task. The waitone () method uses a time-out period as the first optional parameter, in which you can define the maximum time to wait. If the waitone method times out, false is returned.

Code
  1. Static VoidMain (String[] ARGs)
  2. {
  3.  
  4. TakesawhiledelegateT2 = takesawhile;
  5. IasyncresultAR = t2.begininvoke (1, 3000,Null,Null);
  6. While(True)
  7. {
  8. Console. Write (".");
  9. If(AR. asyncwaithandle. waitone (50,False))
  10. {
  11. Console. Writeline ("Can get the result now");
  12. Break;
  13. }
  14. }
  15. IntResult = t2.endinvoke (AR );
  16. Console. Writeline ("Reault: {0 }", Result );
  17. Console. Readline ();
  18.  
  19. }

Here, when the background thread is not completed, the main thread does not use the thread. Sleep (50) method to execute other tasks in the main thread.

Iii. asynchronous callback

Asynchronous callback refers to the process of entrusting a task to a backend thread. After the task ends, a defined method is automatically called without waiting for results in the main thread.

In the third parameter of the begininvoke () method, you can pass a method that meets the requirements of the iasynccallback delegate. After the delegate method is executed, the background thread calls this method. Second, you do not need to wait for the result of the background thread in the main thread.

The iasynccallback delegate defines an iasyncresult type parameter whose return type is void. In the following code, we first define a takesawhilecomplated () method as the callback method.

Code
  1. Public Static VoidTakesawhilecomplated (IasyncresultAR)
  2. {
  3. If(AR =Null)
  4. {
  5. Throw New Argumentnullexception("Ar");
  6. }
  7. TakesawhiledelegateT3 = ar. asyncstateAs Takesawhiledelegate;
  8. Trace. Assert (T3! =Null,"The object type is incorrect");
  9. IntResult = t3.endinvoke (AR );
  10. Console. Writeline ("Result {0 }", Result );
  11. }

Then we start this method in the main thread:

Code
  1. Static VoidMain (String[] ARGs)
  2. {
  3. TakesawhiledelegateT3 = takesawhile;
  4. T3.begininvoke (1, 3000, takesawhilecomplated, T3 );
  5. For(IntI = 0; I <100; I ++)
  6. {
  7. Console. Write (".");
  8. Thread. Sleep (50 );
  9. }
  10.  
  11. Console. Readline ();
  12. }

Run this code and you can see the output in the console.

Here, you only need to delegate the takesawhiledelegate to complete the task, and the takesawhilecomplated method will be called. You do not need to wait for results in the main thread. When using the callback method, you must note that this method is called from the delegate thread rather than from the main thread.

At the same time, the main thread cannot be stopped before the end of the delegate task, unless there is no problem with the delegation thread that stops when the main thread ends.

Download the code in this article:

Http://files.cnblogs.com/zyqgold/ConsoleApplication1.rar

Technorati label: asynchronous Delegation

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.