Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using System. Threading;
Using System. Runtime. Remoting. Messaging;
Namespace asynchronous Delegation
{
/// <Summary>
/// Indicates that a new thread will be generated during asynchronous delegate calls, and the main thread will not be blocked,
/// The premise is that the callback function is used instead of the Delegate. endinvoke method to obtain the result.
/// </Summary>
Class Program
{
Public delegate int AddDel (int x, int y );
Static void Main (string [] args)
{
// Define the delegate
AddDel addDel = new AddDel (AddFunc );
Console. WriteLine ("the main Thread starts to execute... {0}", Thread. CurrentThread. ManagedThreadId );
// Start the asynchronous call delegate
AddDel. BeginInvoke (2, 3, Callback, 2); // Callback function of the third parameter, fourth parameter, and additional parameter
Console. WriteLine ("the main thread has been executed! ");
Console. ReadKey ();
}
Static int AddFunc (int x, int y)
{
Console. WriteLine ("sub-Thread execution: {0}", Thread. CurrentThread. ManagedThreadId );
Thread. Sleep (3000 );
Return x + y;
}
Static void Callback (IAsyncResult ar)
{
AsyncResult asy = (AsyncResult) ar;
// Obtain Proxy Information
AddDel addDel = (AddDel) asy. AsyncDelegate;
// Obtain the returned results
Int result = addDel. EndInvoke (ar );
// Obtain additional parameters
Int otherData = (int) asy. AsyncState;
Console. WriteLine ("sub-thread execution completed! {0}, execution result: {1}, additional parameter: {2} ", Thread. CurrentThread. ManagedThreadId
, Result, otherData );
}
}
}