首先是 Begin 之後直接調用 End 方法,當然中間也可以做其他的操作
class AsyncTest
{
static void Main(string[] args)
{
AsyncDemo demo = new AsyncDemo("jiangnii");
// Execute begin method
IAsyncResult ar = demo.BeginRun(null, null);
// You can do other things here
// Use end method to block thread until the Operation is complete
string demoName = demo.EndRun(ar);
Console.WriteLine(demoName);
}
}
也可以用 IAsyncResult的 AsyncWaitHandle屬性,我在這裡設置為1秒超時
class AsyncTest
{
static void Main(string[] args)
{
AsyncDemo demo = new AsyncDemo("jiangnii");
// Execute begin method
IAsyncResult ar = demo.BeginRun(null, null);
// You can do other things here
// Use AsyncWaitHandle.WaitOne method to block thread for 1 second at most
ar.AsyncWaitHandle.WaitOne(1000, false);
if (ar.IsCompleted)
{
// Still need use end method to get result, but this time it will return immediately
string demoName = demo.EndRun(ar);
Console.WriteLine(demoName);
}
else
{
Console.WriteLine("Sorry, can't get demoName, the time is over");
}
}
}