微软IAsyncResult 接口接口实现异步调用
微软官方文档:
IAsyncResult 接口:https://docs.microsoft.com/zh-cn/dotnet/api/system.iasyncresult?redirectedfrom=MSDN&view=net-6.0
AsyncCallback 委托:https://docs.microsoft.com/zh-cn/dotnet/api/system.asynccallback?view=net-6.0
IAsyncResult 接口在使用委托异步调用方法时返回 AsyncResult ,IAsyncResult; 异步调用由 BeginInvoke 的实现。
首先定义一个委托
//定义一个委托
public delegate string AsyncMethodCaller(int callDuration);
public void DoAsyncMethod()
{
TestAsync.AsyncMethodCaller asyncMethodCaller = new TestAsync.AsyncMethodCaller(TestMethod);
//BeginInvoke实现异步调用
IAsyncResult result = asyncMethodCaller.BeginInvoke(100, null, null);
//AsyncWaitHandle 会阻塞线程,如果不处理结果,仅使用第一句和第二就代码即可。
//如果在winform页面中不想页面卡住,可以只使用前2句。
result.AsyncWaitHandle.WaitOne(100);
// 获取结果
string returnValue = asyncMethodCaller.EndInvoke(result);
//if (result.IsCompleted)也可以先判断线程是否调用结束
// 关闭等待的线程
//result.AsyncWaitHandle.Close();
// 关闭等待的线程
result.AsyncWaitHandle.Close();
}
public string TestMethod(int callDuration)
{
Thread.Sleep(callDuration);
int threadId = Thread.CurrentThread.ManagedThreadId;
return String.Format("The call ManagedThreadId was {0}.", threadId.ToString());
}