Use the AsyncWatiHandle attribute to access the waiting handle. The WaitOne () method blocks the current thread until the asynchronous call thread finishes returning the available handle before executing the current thread.
Program:
[Html]
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using System. Threading;
Namespace AsyncDelegate
{
Class Program
{
Public delegate int TakeSomeTimeDelegate (int data, int MS );
Static void Main (string [] args)
{
TakeSomeTimeDelegate dl = TakeSomeTime;
IAsyncResult ar = dl. BeginInvoke (1,200, null, null );
While (true)
{
Console. WriteLine (".");
Console. WriteLine ("Run in thread:" + Thread. CurrentThread. ManagedThreadId );
If (ar. AsyncWaitHandle. WaitOne (100, false ))
{
Console. WriteLine ("Can get the result now ");
Break;
}
}
// While (! Ar. IsCompleted)
//{
// Console. WriteLine (".");
// Console. WriteLine ("Run in thread:" + Thread. CurrentThread. ManagedThreadId );
// Thread. Sleep (50 );
//}
Int result = dl. EndInvoke (ar );
Console. WriteLine ("Result: {0}", result );
}
Static int TakeSomeTime (int data, int MS)
{
Console. WriteLine ("TakeSomeTime started! ");
Console. WriteLine ("Run in thread:" + Thread. CurrentThread. ManagedThreadId );
Thread. Sleep (MS );
Console. WriteLine ("TakeSomeTime Completed! ");
Return ++ data;
}
}
}
[Html]
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using System. Threading;
Namespace AsyncDelegate
{
Class Program
{
Public delegate int TakeSomeTimeDelegate (int data, int MS );
Static void Main (string [] args)
{
TakeSomeTimeDelegate dl = TakeSomeTime;
IAsyncResult ar = dl. BeginInvoke (1,200, null, null );
While (true)
{
Console. WriteLine (".");
Console. WriteLine ("Run in thread:" + Thread. CurrentThread. ManagedThreadId );
If (ar. AsyncWaitHandle. WaitOne (100, false ))
{
Console. WriteLine ("Can get the result now ");
Break;
}
}
// While (! Ar. IsCompleted)
//{
// Console. WriteLine (".");
// Console. WriteLine ("Run in thread:" + Thread. CurrentThread. ManagedThreadId );
// Thread. Sleep (50 );
//}
Int result = dl. EndInvoke (ar );
Console. WriteLine ("Result: {0}", result );
}
Static int TakeSomeTime (int data, int MS)
{
Console. WriteLine ("TakeSomeTime started! ");
Console. WriteLine ("Run in thread:" + Thread. CurrentThread. ManagedThreadId );
Thread. Sleep (MS );
Console. WriteLine ("TakeSomeTime Completed! ");
Return ++ data;
}
}
}
Running result:
Ar. AsyncWaitHandle. WaitOne () blocks the current thread and executes the current thread again after the asynchronous call thread completes obtaining the available handle.
Author: xuhongwei0411