终止任务的正确方法是什么?

时间:2017-05-26 10:38:21

标签: c# .net multithreading task task-parallel-library

有一个关于立即终止任务的正确方法的问题。 例如,我有以下代码:

public async Task<string> DoAsync()
{
    var result = await Task.Run(() =>
    {
        //Some heavy request here in a row (5 seconds per request)
        DoHeavyRequest(); // 1
        DoHeavyRequest(); // 2
        DoHeavyRequest(); // 3
        DoHeavyRequest(); // 4

        return "success";
    });

    return results;
}

如何在一瞬间取消此任务?例如,我运行任务7秒钟,我期待只有第一个,可能是第二个&#34;重要的请求&#34;将被调用,3-4根本不会被调用。

提前致谢。

1 个答案:

答案 0 :(得分:2)

我建议取消

public async Task<string> DoAsync(CancellationToken token) {
  var result = await Task.Run(() =>  {
    //TODO: you may want to pass token to DoHeavyRequest() and cancel there as well
    token.ThrowIfCancellationRequested();
    DoHeavyRequest(); // 1

    token.ThrowIfCancellationRequested();
    DoHeavyRequest(); // 2

    token.ThrowIfCancellationRequested();
    DoHeavyRequest(); // 3

    token.ThrowIfCancellationRequested();
    DoHeavyRequest(); // 4

    return "success";
  });

  return "results";
}

// Let's preserve the current interface - call without cancellation
public async Task<string> DoAsync() {
  return await DoAsync(CancellationToken.None);
}

...

// Run, wait up to 7 seconds then cancel 
try {
  using (CancellationTokenSource cts = new CancellationTokenSource(7000)) {
    // Task completed, its result is in the result
    string result = await DoAsync(cts.Token);

    //TODO: Put relevant code here 
  }  
catch (TaskCanceledException) { 
  // Task has been cancelled (in this case by timeout)

  //TODO: Put relevant code here  
}