我想调用一个返回IAsyncResult
对象的异步操作,特别是类的GetHostEntry
方法System.Net.Dns
。
我已经明白我应该调用属性的WaitOne
方法来等待某个超时以等待操作完成,但显然我错了,因为这段代码不起作用:AsyncWaitHandle
IAsyncResult
using System;
using System.Net;
static class Program {
class GetHostEntryState {
public IPHostEntry Value {
get;
set;
}
}
static void Main(string[] args) {
string hostName = "somehost";
int timeout = 1000;
var state = new GetHostEntryState();
var asyncResult = Dns.BeginGetHostEntry(hostName, ar => {
((GetHostEntryState)ar.AsyncState).Value = Dns.EndGetHostEntry(ar);
}, state);
if (asyncResult.AsyncWaitHandle.WaitOne(timeout) && asyncResult.IsCompleted) {
if (state.Value == null) {
// we always hit this condition
Console.WriteLine("state.Value == null");
return;
}
foreach (var address in state.Value.AddressList) {
Console.WriteLine(address);
}
} else {
Console.WriteLine("timed out");
}
}
}
msdn 中的示例使用ManualResetEvent
对象进行同步。那有必要吗?如果是这样,AsyncWaitHandle
这里的财产有什么用?