4

这是几个星期以来运行良好的原始代码。在我刚刚进行的测试中,100 次尝试失败了 0 次。

using (var httpClient = new HttpClient())
{
    var tasks = new List<Task>();

    tasks.Add(httpClient.GetAsync(new Uri("..."))
        .ContinueWith(request =>
        {
            request.Result.Content.ReadAsAsync<IEnumerable<Foo>>()
                .ContinueWith(response =>
                {
                    foos = response.Result;
                });
        }));

    tasks.Add(httpClient.GetAsync(new Uri("..."))
        .ContinueWith(request =>
        {
            request.Result.Content.ReadAsAsync<Bar>()
                .ContinueWith(response =>
                {
                    bar = response.Result;
                });
        }));

    await Task.WhenAll(tasks);
}

此代码在 100 次尝试中失败了 9 次,其中一个或两个元组值为null.

var APIresponses = await HttpClientHelper.GetAsync
    <
        IEnumerable<Foo>,
        Bar
    >
    (
        new Uri("..."),
        new Uri("...")
    );

foos = APIresponses.Item1;
bar = APIresponses.Item2;
private static Task GetAsync<T>(HttpClient httpClient, Uri URI, Action<Task<T>> continuationAction)
{
    return httpClient.GetAsync(URI)
        .ContinueWith(request =>
        {
            request.Result.EnsureSuccessStatusCode();

            request.Result.Content.ReadAsAsync<T>()
                .ContinueWith(continuationAction);
        });
}

public static async Task<Tuple<T1, T2>> GetAsync<T1, T2>(Uri URI1, Uri URI2)
{
    T1 item1 = default(T1);
    T2 item2 = default(T2);

    var httpClient = new HttpClient();
    var tasks = new List<Task>()
    {
        GetAsync<T1>(httpClient, URI1, response =>
        {
            item1 = response.Result;
        }),
        GetAsync<T2>(httpClient, URI2, response =>
        {
            item2 = response.Result;
        })
    };

    await Task.WhenAll(tasks);

    return Tuple.Create(item1, item2);
}

将代码修改为如下所示,100 次尝试中将再次失败 0 次。

    await Task.WhenAll(tasks);
    System.Diagnostics.Debug.WriteLine("tasks complete");
    System.Diagnostics.Debug.WriteLine(item1);
    System.Diagnostics.Debug.WriteLine(item2);

    return Tuple.Create(item1, item2);
}

我一直在看这个半个多小时,但我看不出错误在哪里。有人看到吗?

4

3 回答 3

2

要解决对您其他问题的评论,您很少需要混合async/awaitContinueWith。您可以在 lambda 的帮助下执行“fork”逻辑async,例如,问题中的代码可能如下所示:

using (var httpClient = new HttpClient())
{
    Func<Task<IEnumerable<Foo>>> doTask1Async = async () =>
    {
        var request = await httpClient.GetAsync(new Uri("..."));
        return response.Content.ReadAsAsync<IEnumerable<Foo>>();
    };

    Func<Task<IEnumerable<Bar>>> doTask2Async = async () =>
    {
        var request = await httpClient.GetAsync(new Uri("..."));
        return response.Content.ReadAsAsync<IEnumerable<Bar>>();
    };

    var task1 = doTask1Async();
    var task2 = doTask2Async();

    await Task.WhenAll(task1, task2);

    var result1 = task1.Result;
    var result2 = task2.Result;

    // ...
}
于 2014-04-22T10:00:28.627 回答
2

这段代码:

        request.Result.Content.ReadAsAsync<T>()
            .ContinueWith(continuationAction);

返回一个任务,但从不等待该任务(并且没有继续添加它)。因此,该项目可能不会在Task.WhenAll退货前设置。

然而,原来的解决方案似乎有同样的问题。

我的猜测是您正在处理值类型,并且两者都有竞争条件,但是在第二个示例中,您足够早地将值类型(虽然它们仍然是它们的默认值)复制到元组中。在您的其他示例中,您在复制它们或使用它们之前等待足够长的时间,以便设置值的问题继续运行

于 2013-10-04T13:35:01.390 回答
1

编辑:不接受我自己的答案,但留作参考。该代码有效,但有一个问题:ContinueWith 丢失了 SynchronizationContext


感谢@jbl@MattSmith让我走上了正轨。

问题确实是Task.WhenAll不等待延续。解决方案是设置TaskContinuationOptions.AttachedToParent.

所以这

private static Task GetAsync<T>(HttpClient httpClient, Uri URI, Action<Task<T>> continuationAction)
{
    return httpClient.GetAsync(URI)
        .ContinueWith(request =>
        {
            request.Result.EnsureSuccessStatusCode();

            request.Result.Content.ReadAsAsync<T>()
                .ContinueWith(continuationAction);
        });
}

变成这个

private static Task GetAsync<T>(HttpClient httpClient, Uri URI, Action<Task<T>> continuationAction)
{
    return httpClient.GetAsync(URI)
        .ContinueWith(request =>
        {
            request.Result.EnsureSuccessStatusCode();

            request.Result.Content.ReadAsAsync<T>()
                .ContinueWith(continuationAction, TaskContinuationOptions.AttachedToParent);
        }, TaskContinuationOptions.AttachedToParent);
}

MSDN上提供了更多信息:嵌套任务和子任务

于 2013-10-04T15:05:54.070 回答