TPLタスクを中止/キャンセルするにはどうすればいいですか? 質問する

TPLタスクを中止/キャンセルするにはどうすればいいですか? 質問する

スレッドでは、いくつか作成しSystem.Threading.Taskて各タスクを開始します。

.Abort()スレッドを強制終了するを実行しても、タスクは中止されません。

.Abort()を自分のタスクに送信するにはどうすればいいですか?

ベストアンサー1

できません。タスクはスレッドプールのバックグラウンドスレッドを使用します。また、Abortメソッドを使用してスレッドをキャンセルすることは推奨されません。次のブログ投稿キャンセル トークンを使用してタスクをキャンセルする適切な方法を説明しています。次に例を示します。

class Program
{
    static void Main()
    {
        var ts = new CancellationTokenSource();
        CancellationToken ct = ts.Token;
        Task.Factory.StartNew(() =>
        {
            while (true)
            {
                // do some heavy work here
                Thread.Sleep(100);
                if (ct.IsCancellationRequested)
                {
                    // another thread decided to cancel
                    Console.WriteLine("task canceled");
                    break;
                }
            }
        }, ct);

        // Simulate waiting 3s for the task to complete
        Thread.Sleep(3000);

        // Can't wait anymore => cancel this task 
        ts.Cancel();
        Console.ReadLine();
    }
}

おすすめ記事