Using a CancellationToken to cancel a task without explicitly checking within the task?

前端 未结 3 1036
遇见更好的自我
遇见更好的自我 2020-12-21 07:31

Background:

I have a web application which kicks off long running (and stateless) tasks:

var          


        
3条回答
  •  無奈伤痛
    2020-12-21 07:56

    If you actually just have a bunch of method calls you are calling one after the other, you can implement a method runner that runs them in sequence and checks in between for the cancellation.

    Something like this:

    public static void WorkUntilFinishedOrCancelled(CancellationToken token, params Action[] work)
    {
        foreach (var workItem in work)
        {
            token.ThrowIfCancellationRequested();
            workItem();
        }
    }
    

    You could use it like this:

    async Task DoWork(Foo foo)
    {
        WorkUntilFinishedOrCancelled([YourCancellationToken], DoStuff1, DoStuff2, DoStuff3, ...);        
    }
    

    This would essentially do what you want.

提交回复
热议问题