【发布时间】:2009-01-02 10:02:36
【问题描述】:
我通常对部分实现接口持谨慎态度。但是,IAsyncResult 有点特殊,因为它支持几种完全不同的使用模式。您多久使用一次/看到使用AsyncState/AsyncCallback 模式,而不是仅仅调用EndInvoke、使用AsyncWaitHandle 或轮询IsCompleted(讨厌)?
相关问题:Detecting that a ThreadPool WorkItem has completed/waiting for completion。
考虑这个类(非常近似,需要锁定):
public class Concurrent<T> {
private ManualResetEvent _resetEvent;
private T _result;
public Concurrent(Func<T> f) {
ThreadPool.QueueUserWorkItem(_ => {
_result = f();
IsCompleted = true;
if (_resetEvent != null)
_resetEvent.Set();
});
}
public WaitHandle WaitHandle {
get {
if (_resetEvent == null)
_resetEvent = new ManualResetEvent(IsCompleted);
return _resetEvent;
}
public bool IsCompleted {get; private set;}
...
它有WaitHandle(延迟创建,正如IAsyncResult 文档中所述)和IsCompleted,但我看不到AsyncState({return null;}?)的合理实现。那么它实现IAsyncResult有意义吗?请注意,Parallel Extensions 库中的Task 确实实现了IAsyncResult,但只有IsCompleted 是隐式实现的。
【问题讨论】:
标签: c# concurrency asynchronous iasyncresult