将 async/await 转换为 Task.ContinueWith [英] Converting async/await to Task.ContinueWith
问题描述
这个问题是由对这个的评论引发的:
This question was triggered by comments to this one:
如何在没有 Microsoft.Bcl.Async
的情况下将非线性 async/await
代码向后移植到 .NET 4.0?
How to back-port a non-linear async/await
code to .NET 4.0 without Microsoft.Bcl.Async
?
在链接的问题中,我们有一个 WebRequest
操作,如果它一直失败,我们希望重试有限的次数.Async/await
代码可能如下所示:
In the linked question, we have a WebRequest
operation we want to retry for a limited number of times, if it keeps failing. The Async/await
code could look like this:
async Task<HttpWebResponse> GetResponseWithRetryAsync(string url, int retries)
{
if (retries < 0)
throw new ArgumentOutOfRangeException();
var request = WebRequest.Create(url);
while (true)
{
WebResponse task = null;
try
{
task = request.GetResponseAsync();
return (HttpWebResponse)await task;
}
catch (Exception ex)
{
if (task.IsCanceled)
throw;
if (--retries == 0)
throw; // rethrow last error
// otherwise, log the error and retry
Debug.Print("Retrying after error: " + ex.Message);
}
}
}
从第一个想法开始,我会使用 TaskCompletionSource
,就像这样(未经测试):
From the first thought, I'd use TaskCompletionSource
, as something like this (untested):
Task<HttpWebResponse> GetResponseWithRetryAsync(string url, int retries)
{
if (retries < 0)
throw new ArgumentOutOfRangeException();
var request = WebRequest.Create(url);
var tcs = new TaskCompletionSource<HttpWebResponse>();
Action<Task<WebResponse>> proceesToNextStep = null;
Action doStep = () =>
request.GetResponseAsync().ContinueWith(proceedToNextStep);
proceedToNextStep = (prevTask) =>
{
if (prevTask.IsCanceled)
tcs.SetCanceled();
else if (!prevTask.IsFaulted)
tcs.SetResult((HttpWebResponse)prevTask.Result);
else if (--retries == 0)
tcs.SetException(prevTask.Exception);
else
doStep();
};
doStep();
return tcs.Task;
}
问题是,如何在没有TaskCompletionSource
的情况下做到这一点?
The question is, how to do this without TaskCompletionSource
?
推荐答案
我已经找到了不用 async/await
或 TaskCompletionSource
的方法,使用嵌套任务和 Task.Unwrap
代替.
I've figured out how to do it without async/await
or TaskCompletionSource
, using nested tasks and Task.Unwrap
instead.
首先,为了解决@mikez 的评论,这里是 .NET 4.0 的 GetResponseAsync
实现:
First, to address @mikez's comment, here's GetResponseAsync
implementation for .NET 4.0:
static public Task<WebResponse> GetResponseTapAsync(this WebRequest request)
{
return Task.Factory.FromAsync(
(asyncCallback, state) =>
request.BeginGetResponse(asyncCallback, state),
(asyncResult) =>
request.EndGetResponse(asyncResult), null);
}
现在,这里是 GetResponseWithRetryAsync
实现:
Now, here's GetResponseWithRetryAsync
implementation:
static Task<HttpWebResponse> GetResponseWithRetryAsync(string url, int retries)
{
if (retries < 0)
throw new ArgumentOutOfRangeException();
var request = WebRequest.Create(url);
Func<Task<WebResponse>, Task<HttpWebResponse>> proceedToNextStep = null;
Func<Task<HttpWebResponse>> doStep = () =>
{
return request.GetResponseTapAsync().ContinueWith(proceedToNextStep).Unwrap();
};
proceedToNextStep = (prevTask) =>
{
if (prevTask.IsCanceled)
throw new TaskCanceledException();
if (prevTask.IsFaulted && --retries > 0)
return doStep();
// throw if failed or return the result
return Task.FromResult((HttpWebResponse)prevTask.Result);
};
return doStep();
}
这是一个有趣的练习.它有效,但我认为它比 async/await
版本更难遵循.
It's been an interesting exercise. It works, but I think its the way more difficult to follow, than the async/await
version.
这篇关于将 async/await 转换为 Task.ContinueWith的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!