2016-04-28 25 views
2

タスクの実行中にタスクを完全に停止する方法はありますか?タスク実行時のタスクの停止

private async void button1_Click(object sender, EventArgs e) 
{ 
    await Backup(file); 
} 

public async Task Backup(string File) 
{ 
    await Task.Run(() => 
    { 
     1)do something here 

     2)do something here 

     3)do something here 

     }); 
} 
private async void button2_Click(object sender, EventArgs e) 
{ 
    <stop backup> 
} 

私は第二のものの間にタスクを停止したいと言うことは、処理された場合、私はボタン2をクリックし、タスクは、私がキャンセルしたりbutton2_Clickからタスクを終了するにはどうすればよいのプロセス

停止しますか?

+1

https://msdn.microsoft.com/en-us/library/hh160373(v=vs.110).aspx例 – weston

答えて

2
// Define the cancellation token source & token as global objects 
CancellationTokenSource source = new   CancellationTokenSource(); 
CancellationToken token; 

//when button is clicked, call method to run task & include the cancellation token 

private async void button1_Click(object sender, EventArgs e) 
{ 
    token = source.Token; 
    await Backup(file, token); 
} 


public async Task Backup 
(string File, CancellationToken token) 
{ 
    Task t1 = Task.Run(() => 
    { 
    //do something here 
    }, token); 
} 

//cancel button click event handler 
private async void cancelButton_Click(object sender, EventArgs e) 
{ 
    if(source! = null) 
    { 
    source.Cancel(); 
    } 
} 

//tasks 
https://msdn.microsoft.com/en-us/library/system.threading.tasks.task(v=vs.110).aspx 

//CancellationToken 
https://msdn.microsoft.com/en-us/library/system.threading.cancellationtoken(v=vs.110).aspx 
+0

でiはCancellationTokenトークン= NULLでエラーが出ます。 (nullを 'System.Threading.CancellationToken'に変換することはできません。これはnull値ではないためです) –

+0

Taskをインスタンス化するときにsource.Tokenを使用する必要があります。 –

関連する問題