我正在使用 Begin/End 样式方法进行一些异步网络 I/O。(它实际上是针对 Azure 表存储的查询,但我认为这并不重要。)我已经使用ThreadPool.RegisterWaitForSingleObject()
. 据我所知,这工作正常。
因为ThreadPool.RegisterWaitForSingleObject()
需要 aWaitHandle
作为参数,所以我必须开始 I/O 操作,然后执行ThreadPool.RegisterWaitForSingleObject()
. 似乎这引入了 I/O 在我注册等待之前完成的可能性。
简化的代码示例:
private void RunQuery(QueryState queryState)
{
//Start I/O operation
IAsyncResult asyncResult = queryState.Query.BeginExecuteSegmented(NoopAsyncCallback, queryState);
//What if the I/O operation completes here?
queryState.TimeoutWaitHandle = ThreadPool.RegisterWaitForSingleObject(asyncResult.AsyncWaitHandle, QuerySegmentCompleted, asyncResult, queryTimeout, true);
}
private void QuerySegmentCompleted(object opState, bool timedOut){
IAsyncResult asyncResult = opState as IAsyncResult;
QueryState state = asyncResult.AsyncState as QueryState;
//If the I/O completed quickly, could TimeoutWaitHandle could be null here?
//If so, what do I do about that?
state.TimeoutWaitHandle.Unregister(asyncResult.AsyncWaitHandle);
}
处理这个问题的正确方法是什么?我还需要担心Unregister()
AsyncWaitHandle 吗?如果是这样,是否有一种相当简单的方法来等待它被设置?