C # End asynchronous calling of asynchronous programming

Source: Internet
Author: User

When ininvoke and endinvoke are used for asynchronous calls, after begininvoke is called, you can perform the following operations to end asynchronous calls:

· Perform some operations and call endinvoke until the call is completed.

· Use the iasyncresult...:. asyncwaithandle attribute to obtain the waithandle. Use its waitone method to stop execution until the waithandle signal is sent and then call endinvoke.

· Poll iasyncresult returned by begininvoke, determine when the asynchronous call is completed, and then call endinvoke.

· Pass the delegate used for the callback method to begininvoke. After the asynchronous call is completed, the method will be executed on the threadpool thread. This callback method calls endinvoke.

 

Asynchronous Delegation

The following code demonstrates various methods for Asynchronously calling the same long-running method testmethod. The testmethod method will display a console message indicating that it has started to process, sleep for several seconds, and then ended. Testmethod hasOutThis parameter is used to demonstrate how this parameter is added to the begininvoke and endinvoke signatures. It can be processed in the same way.RefParameters.

The definition of testmethod and the delegate named asyncmethodcaller can be used to call testmethod asynchronously. To compile any sample code, you must include the testmethod definition and asyncmethodcaller delegation.

 

using System;using System.Threading; namespace Examples.AdvancedProgramming.AsynchronousOperations{    public class AsyncDemo     {        // The method to be executed asynchronously.        public string TestMethod(int callDuration, out int threadId)         {            Console.WriteLine("Test method begins.");            Thread.Sleep(callDuration);            threadId = Thread.CurrentThread.ManagedThreadId;            return String.Format("My call time was {0}.", callDuration.ToString());        }    }    // The delegate must have the same signature as the method    // it will call asynchronously.    public delegate string AsyncMethodCaller(int callDuration, out int threadId);}

 

 

UseEndinvokeWaiting for asynchronous call

The simplest method of asynchronous execution is to call the ininvoke method of the delegate to start the execution of the method, execute some work on the main thread, and then call the delegate endinvoke method. Endinvoke may block the calling thread because it will not return until the asynchronous call is complete. This technology is very suitable for file or network operations, but because endinvoke will block it, do not call it from the thread serving the user interface.

 

using System;using System.Threading;namespace Examples.AdvancedProgramming.AsynchronousOperations{    public class AsyncMain     {        public static void Main()         {            // The asynchronous method puts the thread id here.            int threadId;            // Create an instance of the test class.            AsyncDemo ad = new AsyncDemo();            // Create the delegate.            AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);            // Initiate the asychronous call.            IAsyncResult result = caller.BeginInvoke(3000,                 out threadId, null, null);            Thread.Sleep(0);            Console.WriteLine("Main thread {0} does some work.",                Thread.CurrentThread.ManagedThreadId);            // Call EndInvoke to wait for the asynchronous call to complete,            // and to retrieve the results.            string returnValue = caller.EndInvoke(out threadId, result);            Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".",                threadId, returnValue);        }    }}

 

UseWaithandleWaiting for asynchronous call

You can use the asyncwaithandle attribute of iasyncresult returned by begininvoke to obtain waithandle. The waithandle signal is sent when the asynchronous call is complete, and you can wait for it by calling the waitone method.

If you use waithandle, you can perform other processing before or after the asynchronous call is complete, before calling the endinvoke retrieval result.

 

 

using System;using System.Threading;namespace Examples.AdvancedProgramming.AsynchronousOperations{    public class AsyncMain     {        static void Main()         {            // The asynchronous method puts the thread id here.            int threadId;            // Create an instance of the test class.            AsyncDemo ad = new AsyncDemo();            // Create the delegate.            AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);            // Initiate the asychronous call.            IAsyncResult result = caller.BeginInvoke(3000,                 out threadId, null, null);            Thread.Sleep(0);            Console.WriteLine("Main thread {0} does some work.",                Thread.CurrentThread.ManagedThreadId);            // Wait for the WaitHandle to become signaled.            result.AsyncWaitHandle.WaitOne();            // Perform additional processing here.            // Call EndInvoke to retrieve the results.            string returnValue = caller.EndInvoke(out threadId, result);            Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".",                threadId, returnValue);        }    }}

 

Round Robin asynchronous call completed

You can use the iscompleted attribute of iasyncresult returned by begininvoke to find out when the asynchronous call is completed. This operation can be performed when asynchronous calling is performed from the service thread on the user interface. After the round robin is completed, the call thread is allowed to continue executing the asynchronous call on the threadpool thread.

 

 

using System;using System.Threading;namespace Examples.AdvancedProgramming.AsynchronousOperations{    public class AsyncMain     {        static void Main() {            // The asynchronous method puts the thread id here.            int threadId;            // Create an instance of the test class.            AsyncDemo ad = new AsyncDemo();            // Create the delegate.            AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);            // Initiate the asychronous call.            IAsyncResult result = caller.BeginInvoke(3000,                 out threadId, null, null);            // Poll while simulating work.            while(result.IsCompleted == false) {                Thread.Sleep(10);            }            // Call EndInvoke to retrieve the results.            string returnValue = caller.EndInvoke(out threadId, result);            Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".",                threadId, returnValue);        }    }

 

Callback method executed when asynchronous call is complete

If the thread that starts the asynchronous call does not need to be the thread that processes the result, the callback method can be executed when the call is completed. The callback method is executed on the threadpool thread.

To use the callback method, you must pass the asynccallback delegate that references the callback method to begininvoke. You can also pass the object that contains the information to be used by the callback method. For example, you can pass the delegate that was used when the call was started so that the callback method can call endinvoke.

 

using System;using System.Threading;namespace Examples.AdvancedProgramming.AsynchronousOperations{    public class AsyncMain     {        // Asynchronous method puts the thread id here.        private static int threadId;        static void Main() {            // Create an instance of the test class.            AsyncDemo ad = new AsyncDemo();            // Create the delegate.            AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);            // Initiate the asychronous call.  Include an AsyncCallback            // delegate representing the callback method, and the data            // needed to call EndInvoke.            IAsyncResult result = caller.BeginInvoke(3000,                out threadId,                 new AsyncCallback(CallbackMethod),                caller );            Console.WriteLine("Press Enter to close application.");            Console.ReadLine();        }        // Callback method must have the same signature as the        // AsyncCallback delegate.        static void CallbackMethod(IAsyncResult ar)         {            // Retrieve the delegate.            AsyncMethodCaller caller = (AsyncMethodCaller) ar.AsyncState;            // Call EndInvoke to retrieve the results.            string returnValue = caller.EndInvoke(out threadId, ar);            Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".",                threadId, returnValue);        }    }}

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.