There are many ways to execute a function in another thread. Here we discuss the use of the BeginInvoke method of delegate. The advantage of this method is that the function is called in another thread, and there is no need to spend too much.
The following is an example of the asynchronous execution method using delegate:
Class Program
{
Static void Main (string [] args)
{
Object syncObject = new object ();
Test test = new Test ();
Int index = 0;
AutoResetEvent signal = new AutoResetEvent (false );
For (int I = 0; I <10; I ++)
{
Test. BeginDoAction (delegate (object sender, EventArgs e)
{
Lock (syncObject)
{
Interlocked. Increment (ref index );
If (index = 10)
Signal. Set ();
Console. WriteLine ("Receive result .");
}
});
}
Console. WriteLine ("Waiting signal .");
Signal. WaitOne ();
Console. WriteLine ("Signaled .");
Console. ReadLine ();
}
}
Public delegate int GetDelegate ();
Class Test
{
Private EventHandler <EventArgs> callbackCompleted;
Public void BeginDoAction (EventHandler <EventArgs> pCallbackCompleted)
{
Console. WriteLine ("Begin do action .");
CallbackCompleted = pCallbackCompleted;
AsyncCallback callback = OnCompleted;
GetDelegate getDelegate = DoAction;
GetDelegate. BeginInvoke (callback, null );
}
Public int DoAction ()
{
Console. WriteLine ("Do action ");
Thread. Sleep (20000 );
Return 1;
}
Private void OnCompleted (IAsyncResult result)
{
GetDelegate getDelegate = (AsyncResult) result). AsyncDelegate as GetDelegate;
Int print = getDelegate. EndInvoke (result );
If (callbackCompleted! = Null)
CallbackCompleted (this, EventArgs. Empty );
}
} Www.2cto.com
The result is as follows, indicating that the function is called asynchronously.
Delegate is a way to asynchronously execute a method on another thread, but its usage also has some limitations. Because delegate actually uses the thread pool for asynchronous execution, therefore, the thread pool itself is restricted by this call method, such as the size of the thread pool or the number of threads it can execute. Therefore, not all Asynchronous Method calls are suitable for using the delegate method.
From Enjoy. NET