为什么原来的任务取消,当它ContinueWith别的东西吗? [英] Why is the original task canceled when it ContinueWith something else?

查看:770
本文介绍了为什么原来的任务取消,当它ContinueWith别的东西吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是连续4周了我一头扎进C#编程。这真的很有趣,但我得到了一个痛苦的屁股:

It's been 4 weeks since I dived into C# programming. It's really fun, however, I got a pain in the ass:

当我开始与 HttpClient.PostAsync()任务孤单,它工作正常。但是,如果我继续用别的东西,在原单任务将被取消,而不是我。 。貌似任务不高兴被继续

When I start a Task with HttpClient.PostAsync() alone, it works fine. But if I continue with something else, the orginal Task will be canceled, not by me. Looks like the Task is not happy about being continued.

Task<HttpResponseMessage> task0;
Task task1;

using (var client = new HttpClient())
{
    HttpContent content = new ByteArrayContent(new byte[]{});

    task0 = client.PostAsync("<valid http address>", content);

    task1 = task0.ContinueWith((t) =>
    {
         // Do nothing
    });
}

task1.Wait();

// I got task0.IsCanceled == true here



我试过

I tried:

1,添加 task0.wait()后,立即 PostAsync()将解决这个问题,但它不是我想要的。因为我需要异步的性能优势,做这将使它完全同步。

1, Add task0.wait() immediately after PostAsync() will solve the issue but it's not what I want. Because I need the performance benefit from async and doing that will make it totally sync.

2,添加 task0.wait() task1.wait()将导致 TaskCanceledExcpetion

3,删除任务1 并等待 task0 都会好的。

3, Remove task1 and wait on task0 will be OK.

4,呼叫 task0.start()将得到开始可能不会被要求承诺式的任务。

4, Call task0.start() will got "Start may not be called on a promise-style task."

所以,PLZ有人告诉我,我做错了。

So, plz someone tell me what am I doing wrong?

PS:

在我问这个问题,我GOOGLE了它好几天。而从StackOverflow的一些问题可能​​看起来培训相关,但事实证明他们是不一样的我的。

Before I asked this question, I had googled it for days. And some questions from StackOverflow might look relevent, but it turned out they were not the same to mine.

谁取消了我的任务是什么?她/他问为什么不执行后续任务。

Who canceled my Task? She/He was asking why the continuation task wasn't executed.

为什么TaskCanceledException发生?她/他被搞乱与其中的CancellationToken我从来没和得到意想不到的结果。

Why does TaskCanceledException occur? She/He was messing up with the CancellationToken which I never did and got unexpected result.

我也看到这个的任务取消并仍然得到任何线索。

I've also read this Task Cancellation and still got no clue.

推荐答案

的HttpClient 最有可能得到处理 PostAsync之前的结束。删除使用语句用于测试目的,并如预期一切都将正常工作。你应该在不同的点配置客户端,当请求完成。

Your HttpClient most likely get's disposed before PostAsync is finished. Remove using statement for test purposes, and everything will work as expected. You should dispose your client at a different point, when request is finished.

此外,许多建议的HttpClient 的重用单个实例尽可能多的,如果你的应用程序逻辑允许它。

Also, many would recommend reuse single instance of HttpClient as much as possible, if your application logic allows it.

这篇关于为什么原来的任务取消,当它ContinueWith别的东西吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆