Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
614 views
in Technique[技术] by (71.8m points)

c# - Converting async/await to Task.ContinueWith

This question was triggered by comments to this one:

How to back-port a non-linear async/await code to .NET 4.0 without Microsoft.Bcl.Async?

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);
        }
    }
}

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;
}

The question is, how to do this without TaskCompletionSource?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I've figured out how to do it without async/await or TaskCompletionSource, using nested tasks and Task.Unwrap instead.

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);
}

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();
}

It's been an interesting exercise. It works, but I think its the way more difficult to follow, than the async/await version.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...