Stopping a task without a CancellationToken

后端 未结 3 1578
我寻月下人不归
我寻月下人不归 2020-12-19 04:22

I am using an external library that has async methods, but not CancellationToken overloads.

Now currently I am using an extension method fr

3条回答
  •  一生所求
    2020-12-19 05:02

    I am using an extension method from another StackOverflow question

    That code is very old.

    The modern AsyncEx approach is an extension method Task.WaitAsync, which looks like this:

    var ct = new CancellationTokenSource(TimeSpan.FromSeconds(2)).Token;
    await myTask.WaitAsync(ct);
    

    I like how the API ended up because it's more clear that it's the wait that is cancelled, not the operation itself.

    Is there any way to "kill" the task without killing the process?

    No.

    The ideal solution is to contact the authors of the library you're using and have them add support for CancellationToken.

    Other than that, you're in the "cancel an uncancelable operation" scenario, which can be solved by:

    • Putting the code in a separate process, and terminating that process on cancellation. This is the only fully safe but most difficult solution.
    • Putting the code in a separate app domain, and unloading that app domain on cancellation. This is not fully safe; terminated app domains can cause process-level resource leaks.
    • Putting the code in a separate thread, and terminating that thread on cancellation. This is even less safe; terminated threads can corrupt program memory.

提交回复
热议问题