简体   繁体   English

取消任务后会发生什么?

[英]What Happens To a Task When It's Cancelled?

I was toying with Await/Async and CancellationTokens. 我在玩Await / Async和CancellationTokens。 My code works, but what happens to the Task when it's Cancelled? 我的代码有效,但是取消任务后会怎样? Is it still taking up resources or is it garbage collected or what? 它仍在占用资源还是被垃圾收集还是什么?

Here is my code: 这是我的代码:

    private CancellationTokenSource _token = new CancellationTokenSource();

    public Form1()
    {
        InitializeComponent();
    }

    async Task<String> methodOne()
    {
        txtLog.AppendText("Pausing for 10 Seconds \n");
        var task = Task.Delay(10000, _token.Token);
        await task;
        return "HTML Returned. \n";

    }

    private async void button1_Click(object sender, EventArgs e)
    {
        try
        {
            var task1 = methodOne();
            await task1;
            txtLog.AppendText(task1.Result + "\n");
            txtLog.AppendText("All Done \n");
        }
        catch (OperationCanceledException oce)
        {
            txtLog.AppendText("Operation was cancelled");
        }
    }

    private void button2_Click(object sender, EventArgs e)
    {
        _token.Cancel();
    }

When a task is cancelled, it completes (in the cancelled state). 取消任务后,任务完成(处于取消状态)。 It acts just like any other object in regards to garbage collection: if you have no references to it, it will be collected. 就垃圾收集而言,它的作用与其他任何对象一样:如果您没有对它的引用,它将被收集。

Note that although Task does implement IDisposable , you don't have to dispose it unless you're using the IAsyncResult.AsyncWaitHandle member . 请注意,尽管Task确实实现了IDisposable但除非使用IAsyncResult.AsyncWaitHandle成员,否则您不必处置它

A task can only be cancelled synchronously (meaning that it must ask "am I cancelled?"), so it's easy for the task to do cleanup (for example by using the using statement). 只能同步取消任务(这意味着它必须询问“我是否已取消?”),因此该任务很容易进行清理(例如,通过使用using语句)。 All the resources it had allocated are then freed by the GC before or later (as always, we don't know when the GC will act, unless we do a GC.Collect(); GC.WaitForFinalizers(); )... 然后,GC会在此之前或之后释放它分配的所有资源(与往常一样,除非我们执行GC.Collect(); GC.WaitForFinalizers();否则我们不知道GC何时执行)...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM