Elegantly handle task cancellation

后端 未结 6 598
花落未央
花落未央 2021-01-03 18:15

When using tasks for large/long running workloads that I need to be able to cancel I often use a template similar to this for the action the task executes:

pu         


        
6条回答
  •  走了就别回头了
    2021-01-03 18:29

    You could do something like this:

    public void DoWork(CancellationToken cancelToken)
    {
        try
        {
            //do work
            cancelToken.ThrowIfCancellationRequested();
            //more work
        }
        catch (OperationCanceledException) when (cancelToken.IsCancellationRequested)
        {
            throw;
        }
        catch (Exception ex)
        {
            Log.Exception(ex);
            throw;
        }
    }
    

提交回复
热议问题