Asynchronous operations in the IAsyncResult design mode are implemented through two methods: The Begin operation name and the End operation name. The two methods start and End asynchronous operations respectively. After the Begin operation name is called, the application can continue to execute commands on the calling thread, while the asynchronous operation is executed on another thread. Each time you call the Begin operation name, the application should also call the End operation name to obtain the operation result.
The Begin operation name method immediately returns the control to the calling thread. If the Begin operation name method raises an exception, an exception is thrown before the asynchronous operation is started. If the Begin operation name method causes an exception, it means that the callback method is not called.
The End operation name method can End the asynchronous operation. The Return Value of the End operation name method is of the same type as that of the synchronous copy, and is specific to asynchronous operations. The End operation name method is called from the main thread of the application to Prevent the application from executing the operation until the operation is completed.
IAsyncResult ar = asynchronous object. BeginXXX (,); asynchronous object. EndXXX (ar); otherthing
It can be seen that the correct implementation of the End operation name method should use the WaitHandle of the returned IAsyncResult object, or use IsCompleted Round Robin to wait for asynchronous execution to complete and process. For verification, I used Reflector to view the FileStream EndRead method.
(asyncResult == ArgumentNullException( (! FileStreamAsyncResult result = asyncResult ((result == ) || ( == Interlocked.CompareExchange( result._EndXxxCalled, , NativeOverlapped* nativeOverlappedPtr = (nativeOverlappedPtr != (result._errorCode != __Error.WinIOError(result._errorCode, Path.GetFileName( (result._numBytes + }
The End operation method is required in asynchronous programming, even if the End operation method does not return any value (may cause memory leakage or other unknown exceptions ). Exercise caution when using a simple asynchronous programming method. Use AsyncCallback (call the End operation method) in the Begin operation method. In this case, you do not need to call the End operation method again, the code runs smoothly, but it may be too late to execute the AsyncCallback program.
In addition, if there is no otherthing between the Begin operation method and the End operation method, or the rest of the work must wait until the End operation method is complete, asynchronous (meaningless) is not recommended at this time ).