CancellationToken and CancellationTokenSource-How to use it?

后端 未结 3 1983
北荒
北荒 2021-01-02 12:23

I have a UI button called Load. It spawns a thread, which in turn spawns a task. There is a wait on the task, and if it expires the task gets cancelled. The Load button is n

3条回答
  •  囚心锁ツ
    2021-01-02 12:35

    This will do it:

        private CancellationTokenSource _cancelTasks;
    
        // this starts your process
        private void DoStuff()
        {
            _cancelTasks = new CancellationTokenSource();
    
            var task = new Task(() => { /* your actions here */ }, _cancelTasks.Token);
            task.Start();
    
            if (!task.Wait(5000)) _cancelTasks.Cancel();
        }
    

提交回复
热议问题