2013-08-21 97 views
6

我正在等待/ 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(); 
    } 

回答

0

任务只能被同步取消(即它必须问“我该取消了?”),所以很容易的任务,通过做清理(例如使用using声明)。所有分配的资源在之前或之后被GC释放(一如既往,我们不知道GC何时会采取行动,除非我们做了GC.Collect(); GC.WaitForFinalizers();)...

相关问题