当它被取消时会发生什么?

时间:2013-08-21 11:47:06

标签: c# .net

我正在玩Await / Async和CancellationTokens。我的代码有效,但是当它被取消时会发生什么?它仍在占用资源还是垃圾收集或什么?

这是我的代码:

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

2 个答案:

答案 0 :(得分:2)

取消任务时,它完成(处于取消状态)。它就像垃圾收集中的任何其他对象一样:如果你没有引用它,它将被收集。

请注意,虽然Task确实实现了IDisposableyou don't have to dispose it unless you're using the IAsyncResult.AsyncWaitHandle member

答案 1 :(得分:0)

任务只能同步取消(意味着它必须询问“我被取消了吗?”),因此任务很容易进行清理(例如使用using语句)。之前或之后,GC已经分配了所有已分配的资源(一如既往,我们不知道GC何时会采取行动,除非我们执行GC.Collect(); GC.WaitForFinalizers();)...

相关问题