Elegantly handle task cancellation

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

    Here is how you elegantly handle Task cancellation:

    Handling "fire-and-forget" Tasks

    var cts = new CancellationTokenSource( 5000 );  // auto-cancel in 5 sec.
    Task.Run( () => {
        cts.Token.ThrowIfCancellationRequested();
    
        // do background work
    
        cts.Token.ThrowIfCancellationRequested();
    
        // more work
    
    }, cts.Token ).ContinueWith( task => {
        if ( !task.IsCanceled && task.IsFaulted )   // suppress cancel exception
            Logger.Log( task.Exception );           // log others
    } );
    

    Handling await Task completion / cancellation

    var cts = new CancellationTokenSource( 5000 ); // auto-cancel in 5 sec.
    var taskToCancel = Task.Delay( 10000, cts.Token );  
    
    // do work
    
    try { await taskToCancel; }           // await cancellation
    catch ( OperationCanceledException ) {}    // suppress cancel exception, re-throw others
    

提交回复
热议问题