当任务被取消时会发生什么?

7
我正在尝试使用Await/Async和CancellationTokens。我的代码可以运行,但是当Task被取消时会发生什么?它是否仍在占用资源,还是被垃圾回收了?
这是我的代码:
    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个回答

2

0
一个任务只能同步取消(意味着它必须询问“我被取消了吗?”),因此任务很容易进行清理(例如使用using语句)。然后,所有分配的资源都将在GC之前或之后被释放(与往常一样,除非我们执行GC.Collect(); GC.WaitForFinalizers();,否则我们不知道GC何时会起作用)...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接