BeginInvoke and EndInvoke change a synchronous method to asynchronous execution. The transformation process involves three steps:
· Add a delegate corresponding to the method;
· Add a callback function of the AsyncCallback delegate type (call EndInvoke in the function body to obtain the return value );
· Pass the method parameters, callback functions, and delegate variables to BeginInvoke;
The following is a simple example:
The code is as follows: |
Copy code |
Public class Test { /// <Summary> /// Original method /// </Summary> /// <Returns> </returns> Private int Todo () { Return 100; }
/// <Summary> /// Add the delegate corresponding to the method /// </Summary> /// <Returns> </returns> Delegate int TodoHandler (); /// <Summary> /// Add a callback function of the AsyncCallback delegate type /// </Summary> /// <Param name = "ar"> </param> Private void TodoCallback (IAsyncResult ar) { TodoHandler handler = (TodoHandler) ar. AsyncState; Console. WriteLine (handler. EndInvoke (ar )); } /// <Summary> /// Call example /// </Summary> Public void InvokeTest () { TodoHandler handler = new TodoHandler (Todo ); Handler. BeginInvoke (TodoCallback, handler ); } } |
Refer to the naming methods BeginXXX and EndXXX for many asynchronous classes and make slight changes to the preceding classes:
The code is as follows: |
Copy code |
Public class Test { Public int Todo (int a, int B) { Return a + B; }
Private delegate int TodoHandler (int a, int B ); Private TodoHandler _ todo = null; Public Test () { _ Todo = Todo; } Public IAsyncResult BeginTodo (int a, int B, AsyncCallback callback, object state) { Return _ todo. BeginInvoke (a, B, callback, state ); } Public int EndTodo (IAsyncResult ar) { Return _ todo. EndInvoke (ar ); } } Public class Program { Static void TodoCallback (IAsyncResult ar) { Test test = (Test) ar. AsyncState; Console. WriteLine (test. EndTodo (ar )); } Static public void Main (string [] args) { Test test = new Test (); Test. BeginTodo (2, 3, TodoCallback, test ); Console. ReadKey (); } } |
The BeginTodo method returns the IAsyncResult type, which is called by someone on the Internet:
The code is as follows: |
Copy code |
Static public void Main (string [] args) { Test test = new Test (); IAsyncResult result = test. BeginTodo (2, 3, null, null ); Console. WriteLine (test. EndTodo (result ));
Console. ReadKey (); } |