2016-05-28 62 views
-1

我有此代碼後的運行狀態:任務仍然是在我的WPF應用程序關閉

this.Closing += WindowOnClosing; 
CancellationTokenSource cts = new CancellationTokenSource(); 

private void func() 
{ 
    Task task = new Task.Factory.Start(() => 
    { 
     // long running code... 
    }), cts.Token); 
    await task; 
} 

private void WindowOnClosing(CancelEventArgs e) 
{ 
    cts.Cancel(); 
} 

但whenI關閉窗口,任務仍然處於運行狀態。

+0

http://stackoverflow.com/questions/10134310/how-to-cancel-a-task-in-await – mohsen

+1

您應該取消關閉'WindowOnClosing'處理程序併爲任務設置一個延續,以關閉任務取消時的窗口。 –

回答

2

首先,你不應該在這種情況下使用StartNew;改爲使用Task.Run。正如我在我的博客上解釋的,StartNew is dangerous。 (我假設你的實際代碼是使用StartNew,因爲new Task.Factory.Start沒有任何意義)。

二,在我的blog post on Delegate Tasks, I explain how the CancellationToken parameter of both StartNew and Run is misleading

You keep using that cancellation token there. I do not think it means what you think it means.

具體而言,僅CancellationToken取消調度委託的;它不會取消委託本身。你必須要取消響應在自己的代碼:

private void func() 
{ 
    var token = cts.Token; 
    Task task = Task.Run(() => 
    { 
    ... 
    token.ThrowIfCancellationRequested(); // Occasionally do this. 
    ... 
    }); 
    await task; 
} 
+0

這隻能解釋他爲什麼永遠不會期望任務一旦開始運行就被取消。這並沒有解釋,爲什麼他也不能指望應用程序完成時的取消狀態。必須等待這項任務 –

-1

我認爲取消任務後,您應該等待取消:

task.Wait();

也在這裏是有用的:

https://msdn.microsoft.com/en-us/library/dd997396%28v=vs.110%29.aspx

+2

除了長時間凍結其程序的用戶界面外,其他任何事情都不會成功;它絕不會取消後臺任務。 – Servy

+0

它不取消任務,其發送取消標誌後,只是等待響應任務,因爲任務可能在工作,第一次看到取消標誌後,它停止任務,畢竟它在MSDN ... –

+0

不,OP代碼的問題在於他實際上並沒有取消任務。這是*可取的,他不同步等待它。添加只會打破代碼*甚至更多*。它不能解決實際問題,並且在添加或不添加實際解決方案時都會產生積極的影響。 – Servy

相關問題