【发布时间】:2015-10-21 20:09:04
【问题描述】:
以下之间有什么区别(如果有的话):
_listener = new HttpListener();
// Wait for an incoming request, then start a new task
// that executes ProcessContext()
var httpctx = await _listener.GetContextAsync();
await Task.Run(() => ProcessContext(httpctx));
/* -- or -- */
// Use ContinueWith to pass the incoming request to ProcessContext()
await _listener.GetContextAsync().ContinueWith(async (tsk) => {
if (tsk.Status != TaskStatus.RanToCompletion) Debug.Assert(false);
await ProcessContext(tsk.Result);
});
第一种方法需要一个笨拙的闭包来将上下文传递给新任务,仅凭这一点我倾向于认为第二种方法更好。不过,我仍然是异步的新手,所以我可能是错的。
总体目标是让任务持续等待 GetContextAsync 的结果:
async Task Listen()
{
while (_listener != null && _listener.IsListening)
{
// Use one of the methods above to get the context
// and pass that context to a new task. This allows
// the current task to loop around and immediately
// resume listening for incoming requests
}
}
【问题讨论】:
标签: c# .net async-await task-parallel-library httplistener