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

前端 未结 5 685
猫巷女王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:46

    Task.Wait() waits up to specified period for task completion and returns whether the task completed in the specified amount of time (or earlier) or not. The task itself is not modified and does not rely on waiting.

    Read nice series: Parallelism in .NET, Parallelism in .NET – Part 10, Cancellation in PLINQ and the Parallel class by Reed Copsey

    And: .NET 4 Cancellation Framework / Parallel Programming: Task Cancellation

    Check following code:

    var cts = new CancellationTokenSource();
    
    var newTask = Task.Factory.StartNew(state =>
                               {
                                  var token = (CancellationToken)state;
                                  while (!token.IsCancellationRequested)
                                  {
                                  }
                                  token.ThrowIfCancellationRequested();
                               }, cts.Token, cts.Token);
    
    
    if (!newTask.Wait(3000, cts.Token)) cts.Cancel();
    

提交回复
热议问题