The. NET Framework provides two design patterns for asynchronous operations: asynchronous operations that use IAsyncResult objects and asynchronous operations that use events. First, learn the former.
Overview
IAsyncResult Asynchronous design mode implements an asynchronous invocation of the original synchronization method through two methods named Beginoperationname and Endoperationname, such as the FileStream class provides BeginRead and EndRead methods To read bytes asynchronously from files, which are asynchronous versions of the Read method
The Begin method contains any parameters in the synchronization method signature, in addition to two other parameters: a AsyncCallback delegate and a user-defined state object. The delegate is used to invoke the callback method, which is used to pass state information to the callback method. This method returns an object that implements the IAsyncResult interface
The end method ends the asynchronous operation and returns the result, so it contains the ref and out parameters in the synchronization method signature, and the return value type is the same as the synchronization method. The method also includes a IAsyncResult parameter for obtaining information about whether an asynchronous operation is complete, and, of course, must pass in the object instance returned by the corresponding Begin method when used
If you want to block an application after you begin an asynchronous operation, you can call the end method directly, which prevents the application from continuing until the asynchronous operation completes. You can also use IAsyncResult's AsyncWaitHandle property to invoke methods such as WaitOne in it to block threads. There is little difference between the two methods, except that the former must wait and the latter can set the wait timeout
If you do not block the application, you can determine whether the operation is complete by the iscompleted state of the IAsyncResult, or use the AsyncCallback delegate to end the asynchronous operation. The AsyncCallback delegate contains a IAsyncResult signature, and the callback method calls the end method internally to get the result of the operation execution
Try
First, get acquainted with today's protagonist, IAsyncResult interface
public interface IAsyncResult
{
object AsyncState { get; }
WaitHandle AsyncWaitHandle { get; }
bool CompletedSynchronously { get; }
bool IsCompleted { get; }
}