Does Task.Wait(int) stop the task if the timeout elapses without the task finishing?

前端 未结 5 677
猫巷女王i
猫巷女王i 2020-12-02 23:12

I have a task and I expect it to take under a second to run but if it takes longer than a few seconds I want to cancel the task.

For example:

Task          


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-02 23:21

    If you want to cancel a Task, you should pass in a CancellationToken when you create the task. That will allow you to cancel the Task from the outside. You could tie cancellation to a timer if you want.

    To create a Task with a Cancellation token see this example:

    var tokenSource = new CancellationTokenSource();
    var token = tokenSource.Token;
    
    var t = Task.Factory.StartNew(() => {
        // do some work
        if (token.IsCancellationRequested) {
            // Clean up as needed here ....
        }
        token.ThrowIfCancellationRequested();
    }, token);
    

    To cancel the Task call Cancel() on the tokenSource.

提交回复
热议问题