C # Asynchronous invocation

Source: Internet
Author: User
Tags net thread tidy

Let's start with a simple example:

    1. Xiao Ming in boiling water, and so on after the boil, will pour water into the thermos, and then began to tidy up the housework
    2. Xiaowen in the process of boiling water, cleaning up the housework, and so on after the boil, put down the hands of housework, the boiling water into the thermos, and then continue to tidy up the housework

This is also a common situation in daily life, the efficiency of the small text is significantly higher than xiaoming. From the perspective of C # program execution, Xiaoming uses synchronous processing, and Xiaowen uses asynchronous processing mode.

In synchronous processing, transactions are processed one at a time, while asynchronous means that the child operations are separated from the main operation and the master operation continues, and the child operation notifies the main operation when the processing is complete.

In C #, it is done asynchronously through a delegate. Take a look at the following example:

  1. Class Program
  2. {
  3. static TimeSpan boil ()
  4. {
  5. Console.WriteLine ("kettle: Start boiling water ...");
  6. Thread.Sleep (6000);
  7. Console.WriteLine ("Kettle: the water is boiling!"   ");
  8. return timespan.minvalue;
  9. }
  10. delegate TimeSpan Boilingdelegate ();
  11. static void Main (string[] args)
  12. {
  13. Console.WriteLine ("Xiao Wen: Put the kettle on the stove");
  14. Boilingdelegate d = new boilingdelegate (boil);
  15. IAsyncResult result = D.begininvoke (boilingfinishedcallback, null);
  16. Console.WriteLine ("Xiao Wen: Start tidying up the housework ...");
  17. For (int i = 0; i <; i++)
  18. {
  19. Console.WriteLine ("Xiao Wen: finishing the first {0} items housework ...", i + 1);
  20. Thread.Sleep (1000);
  21. }
  22. }
  23. static void Boilingfinishedcallback (IAsyncResult result)
  24. {
  25. AsyncResult AsyncResult = (AsyncResult) result;
  26. Boilingdelegate del = (boilingdelegate) asyncresult.asyncdelegate;
  27. Del. EndInvoke (result);
  28. Console.WriteLine ("Xiao Wen: pouring hot water into a thermos bottle");
  29. Console.WriteLine ("Xiao Wen: continue to tidy up the housework");
  30. }
  31. }

The example above is an example of the simplest asynchronous invocation, without any parameter passing on the asynchronous calling function and a return value check. This example reflects the flow of water boiling water, first xiaowen the kettle on the stove, after the definition of the trust, the use of BeginInvoke method to start an asynchronous call, that is, the kettle began to boil water, so the small article began to tidy up the housework. After the water is fired, the async model of C # triggers the callback function specified by the BeginInvoke method, which is defined by the callback function when the water is fired, and xiaowen the water into the thermos and continues to tidy up the housework.

Thus, implementing an asynchronous call in C # is not complex, first creating an asynchronous handler and defining a delegate for it, and then using the BeginInvoke method of the delegate when calling the function, specifying the callback function when the function is finished (if the completion event does not need to be handled, You can give a null value) and specify the desired parameter (or null if there are no arguments); Finally, the completion event is processed in the callback function.

Note that the EndInvoke call in the previous callback function EndInvoke causes the calling thread to block until the asynchronous function processing is complete. Obviously, the EndInvoke used immediately after BeginInvoke is equivalent to the synchronous call.

The return value of the EndInvoke call is also the return value of the asynchronous handler function. We change the program slightly to change the boil method to the following form:

    1. Static TimeSpan Boil ()
    2. {
    3. DateTime begin = DateTime.Now;
    4. Console.WriteLine ("kettle: Start boiling water ...");
    5. Thread.Sleep (6000);
    6. Console.WriteLine ("Kettle: the water is boiling!"   ");
    7. return datetime.now-begin;
    8. }

Then change the boilingfinishedcallback to the following form:

    1. static void  Boilingfinishedcallback (Iasyncresult result)   
    2. {  
    3.     asyncresult asyncresult =  (AsyncResult) result;   
    4.     BoilingDelegate del =  (boilingdelegate) Asyncresult.asyncdelegate;   
    5.     console.writeline (
    6.     console.writeline (
    7.     console.writeline ( " Xiaowen: Continue to tidy up the housework ");   
    8. }   

Then we can get the time value returned by the boil asynchronous handler when EndInvoke. In fact, if the defined Boilingdelegate delegate has a parameter list, we can also pass the required parameters to the asynchronous handler at BeginInvoke. The signature of the Begininvoke/endinvoke function is related to defining their delegate signature.

Note: In the modified Boilingfinishedcallback method, in order to get the delegate instance to get the return value of the asynchronous handler, we used the following transformation:

    1. AsyncResult AsyncResult = (AsyncResult) result;
    2. Boilingdelegate del = (boilingdelegate) asyncresult.asyncdelegate;

This is to get the entity that invokes the delegate of the asynchronous handler function.

. NET handles asynchronous function calls, which are actually done through threads. This process has the following characteristics:

    • The asynchronous function is done by the thread, which is the thread. NET threads in a thread pool
    • Typically, the. NET thread pool has 500 threads (of course, this number can be set), and each time the call to BeginInvoke begins asynchronous processing, the asynchronous handler is executed by a thread in the thread pool , and the user cannot control which thread is responsible for executing
    • Due to the limited number of threads in the thread pool, the new call request will cause the function to wait for the free thread to occur when the pool is fully occupied. At this point, the efficiency of the program will be affected

To verify these features, see the following procedure:

  1. Class Program
  2. {
  3. delegate void MethodInvoker ();
  4. static void Foo ()
  5. {
  6. int intavailablethreads, intavailableioasynthreds;
  7. Threadpool.getavailablethreads (outintavailablethreads,
  8. Out intavailableioasynthreds);
  9. string strmessage =
  10. String.Format (@ is Thread Pool: {0},
  11. Thread Id: {1} free Threads {2} ",
  12. Thread.CurrentThread.IsThreadPoolThread.ToString (),
  13. Thread.CurrentThread.GetHashCode (),
  14. Intavailablethreads);
  15. Console.WriteLine (strmessage);
  16. Thread.Sleep (10000);
  17. return;
  18. }
  19. static void Callfoo ()
  20. {
  21. MethodInvoker SimpleDelegate =
  22. new MethodInvoker (Foo);
  23. For (int i = 0; i < i++)
  24. {
  25. Simpledelegate.begininvoke (null, null);
  26. }
  27. }
  28. static void Main (string[] args)
  29. {
  30. Threadpool.setmaxthreads (10, 10);
  31. Callfoo ();
  32. Console.ReadLine ();
  33. }
  34. }

This program sets the maximum number of threads in the thread pool to 10 at the beginning, and then makes 15 asynchronous calls, with each asynchronous call resting for 10 seconds as the time it takes to process itself. From the execution of the program we can see that after the current 10 asynchronous calls are fully started, a new asynchronous call will wait (note: Not the main thread is waiting) until the thread pool is idle.

C # Asynchronous invocation

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.