所以看起来没有内置选项,我出去尝试尽我所能做我想要的实验。事实证明,要使这项工作与旧异步模式的其他用户大致相同,还有很多工作要做。
public class AsyncQueue<T>
{
private readonly ConcurrentQueue<T> queue;
private readonly ConcurrentQueue<DequeueAsyncResult> dequeueQueue;
private class DequeueAsyncResult : IAsyncResult
{
public bool IsCompleted { get; set; }
public WaitHandle AsyncWaitHandle { get; set; }
public object AsyncState { get; set; }
public bool CompletedSynchronously { get; set; }
public T Result { get; set; }
public AsyncCallback Callback { get; set; }
}
public AsyncQueue()
{
dequeueQueue = new ConcurrentQueue<DequeueAsyncResult>();
queue = new ConcurrentQueue<T>();
}
public void Enqueue(T item)
{
DequeueAsyncResult asyncResult;
while (dequeueQueue.TryDequeue(out asyncResult))
{
if (!asyncResult.IsCompleted)
{
asyncResult.IsCompleted = true;
asyncResult.Result = item;
ThreadPool.QueueUserWorkItem(state =>
{
if (asyncResult.Callback != null)
{
asyncResult.Callback(asyncResult);
}
else
{
((EventWaitHandle) asyncResult.AsyncWaitHandle).Set();
}
});
return;
}
}
queue.Enqueue(item);
}
public IAsyncResult BeginDequeue(int timeout, AsyncCallback callback, object state)
{
T result;
if (queue.TryDequeue(out result))
{
var dequeueAsyncResult = new DequeueAsyncResult
{
IsCompleted = true,
AsyncWaitHandle = new EventWaitHandle(true, EventResetMode.ManualReset),
AsyncState = state,
CompletedSynchronously = true,
Result = result
};
if (null != callback)
{
callback(dequeueAsyncResult);
}
return dequeueAsyncResult;
}
var pendingResult = new DequeueAsyncResult
{
AsyncState = state,
IsCompleted = false,
AsyncWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset),
CompletedSynchronously = false,
Callback = callback
};
dequeueQueue.Enqueue(pendingResult);
Timer t = null;
t = new Timer(_ =>
{
if (!pendingResult.IsCompleted)
{
pendingResult.IsCompleted = true;
if (null != callback)
{
callback(pendingResult);
}
else
{
((EventWaitHandle)pendingResult.AsyncWaitHandle).Set();
}
}
t.Dispose();
}, new object(), timeout, Timeout.Infinite);
return pendingResult;
}
public T EndDequeue(IAsyncResult result)
{
var dequeueResult = (DequeueAsyncResult) result;
return dequeueResult.Result;
}
}
我不太确定该属性的同步IsComplete
性,并且我不太关心如何在后续调用中dequeueQueue
清理唯一的。Enqueue
我也不确定何时是发出等待句柄信号的正确时间,但这是迄今为止我得到的最佳解决方案。
请不要以任何方式考虑此生产质量代码。我只是想展示我如何在不等待锁的情况下保持所有线程旋转的一般要点。我确信这充满了各种边缘情况和错误,但它满足了要求,我想回馈遇到这个问题的人。