【发布时间】:2012-09-17 01:55:03
【问题描述】:
如何在没有阻塞线程和没有 TPL' ContinueWith 的情况下执行等待?例如。在 3.5 中?我知道 TPL 的 3.5 移植版本(由 RX 团队提供),但我很想知道 - 我可以使用哪些线程原语(...... TPL 的场景是什么)。 TPL 中有哪些 ContinueWith 替代方案?
// 这个handler会在异步IO操作期间阻塞线程吗?
public class AsyncHandler : IHttpAsyncHandler
{
public void ProcessRequest(HttpContext ctx)
{
// not used
}
public bool IsReusable
{
get { return false; }
}
public IAsyncResult BeginProcessRequest(HttpContext ctx,
AsyncCallback cb,
object obj)
{
AsyncRequestState reqState =
new AsyncRequestState(ctx, cb, obj);
AsyncRequest ar = new AsyncRequest(reqState);
ThreadStart ts = new ThreadStart(ar.ProcessRequest);
Thread t = new Thread(ts);
t.Start();
return reqState;
}
public void EndProcessRequest(IAsyncResult ar)
{
AsyncRequestState ars = ar as AsyncRequestState;
if (ars != null)
{
// Some cleanup
}
}
}
class AsyncRequestState : IAsyncResult
{
public AsyncRequestState(HttpContext ctx,
AsyncCallback cb,
object extraData)
{
_ctx = ctx;
_cb = cb;
_extraData = extraData;
}
internal HttpContext _ctx;
internal AsyncCallback _cb;
internal object _extraData;
private bool _isCompleted = false;
private ManualResetEvent _callCompleteEvent = null;
internal void CompleteRequest()
{
_isCompleted = true;
lock (this)
{
if (_callCompleteEvent != null)
_callCompleteEvent.Set();
}
if (_cb != null)
_cb(this);
}
public object AsyncState
{ get { return (_extraData); } }
public bool CompletedSynchronously
{ get { return (false); } }
public bool IsCompleted
{ get { return (_isCompleted); } }
public WaitHandle AsyncWaitHandle
{
get
{
lock (this)
{
if (_callCompleteEvent == null)
_callCompleteEvent = new ManualResetEvent(false);
return _callCompleteEvent;
}
}
}
}
class AsyncRequest
{
private AsyncRequestState _asyncRequestState;
public AsyncRequest(AsyncRequestState ars)
{
_asyncRequestState = ars;
}
public void ProcessRequest()
{
//calling webservice or executing sql command asynchronously
AsyncIOOperationWithCallback(state =>
{
((AsyncRequestState)state.Context)._ctx.Response.Write("Operation completed");
_asyncRequestState.CompleteRequest();
}, _asyncRequestState);
}
}
【问题讨论】:
-
如何使用信号结构
-
究竟什么是“非阻塞等待”?
-
你还想等什么?
标签: c# asynchronous task-parallel-library wait