Elegantly handle task cancellation

后端 未结 6 642
花落未央
花落未央 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:35

    I am not entirely sure of what you are trying to achieve here but I think the following pattern might help

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

    You might have observed that I have removed the throw statement from here. This will not throw the exception but will simply ignore it.

    Let me know if you intend to do something else.

    There is yet another way which is quite close to what you have exhibited in your code

        catch (Exception ex)
        {
            if (!ex.GetType().Equals()
            {
                Log.Exception(ex);
    
            }
        }
    

提交回复
热议问题