In this paper, the method of asynchronous invocation in C # is presented, and the principle of it is analyzed in depth, which is now shared by the tutorial for everyone's reference. Specific as follows:
First, let's look at a simple example:
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
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:
Class program{ static TimeSpan boil () { Console.WriteLine ("Kettle: Start boiling water ..."); Thread.Sleep (6000); Console.WriteLine ("Kettle: the water is boiling!" "); return timespan.minvalue; } Delegate TimeSpan Boilingdelegate (); static void Main (string[] args) { Console.WriteLine: Put the kettle on the Stove "); Boilingdelegate d = new boilingdelegate (boil); IAsyncResult result = D.begininvoke (boilingfinishedcallback, null); Console.WriteLine ("Xiao Wen: Start tidying up the housework ..."); for (int i = 0; i <; i++) { Console.WriteLine ("Small text: Tidying up the first {0} items housework ...", i + 1); Thread.Sleep (+); } } static void Boilingfinishedcallback (IAsyncResult result) { AsyncResult AsyncResult = (AsyncResult) result; Boilingdelegate del = (boilingdelegate) asyncresult.asyncdelegate; Del. EndInvoke (result); Console.WriteLine ("Xiao Wen: pouring hot water into a thermos bottle"); Console.WriteLine ("Xiao Wen: continue to tidy up the housework");} }
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:
Static TimeSpan Boil () { DateTime begin = DateTime.Now; Console.WriteLine ("Kettle: Start boiling water ..."); Thread.Sleep (6000); Console.WriteLine ("Kettle: the water is boiling!" "); return datetime.now-begin;}
Then change the boilingfinishedcallback to the following form:
static void Boilingfinishedcallback (IAsyncResult result) { AsyncResult AsyncResult = (AsyncResult) result; Boilingdelegate del = (boilingdelegate) asyncresult.asyncdelegate; Console.WriteLine ("Boil the water for a total of {0} time"), Del. EndInvoke (Result)); Console.WriteLine ("Xiao Wen: pouring hot water into a thermos bottle"); Console.WriteLine ("Xiao Wen: continue to tidy up the housework");}
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:
AsyncResult AsyncResult = (AsyncResult) result; 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:
1. The asynchronous function is done by the thread, which is the thread. NET threads in a thread pool
2. Typically,. 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
3. 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:
Class program{ delegate void MethodInvoker (); static void Foo () { int intavailablethreads, intavailableioasynthreds; Threadpool.getavailablethreads (out intavailablethreads, out intavailableioasynthreds); String strmessage = String.Format (@ "is the thread Pool: {0}, thread Id: {1} free Threads {2}", thread.currentthread.i Sthreadpoolthread.tostring (), Thread.CurrentThread.GetHashCode (), intavailablethreads); Console.WriteLine (strmessage); Thread.Sleep (10000); return; } static void Callfoo () { MethodInvoker simpledelegate = new MethodInvoker (Foo); for (int i = 0; i < i++) { simpledelegate.begininvoke (null, NULL);} } static void Main (string[] args) { threadpool.setmaxthreads (ten); Callfoo (); Console.ReadLine (); }}
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.
I hope this article is helpful to everyone's C # programming.
In addition to the Declaration,
Running GuestArticles are original, reproduced please link to the form of the address of this article
Example of asynchronous invocation of C # Basics Tutorial
This address: http://www.paobuke.com/develop/c-develop/pbk23543.html
Related content C # current system time acquisition and time format details the SMTP client does not pass authentication and other error solutions share C # DataGridView dynamically add rows and add columns. NET implementation of the regular sending of mail code (two ways)
Random probability selection algorithm for game development C # implements a fast reading of txt text data into Excel C # file and Byte stream conversion method comparison analysis of C # sorting algorithm
Example of asynchronous invocation of C # Basics Tutorial