How can I stop async Process by CancellationToken?

后端 未结 1 1327
闹比i
闹比i 2020-12-11 03:42

I found beneath code for execute some process without freezing UI. This code is executed when \'Start Work\' button is pressed. And I think users would stop this work by \'S

相关标签:
1条回答
  • 2020-12-11 04:02

    The simple answer is that you can just call process.Kill() when the token is canceled:

    cancellationToken.Register(() => process.Kill());
    

    But there are two problems with this:

    1. If you attempt to kill a process that doesn't exist yet or that has already terminated, you get an InvalidOperationException.
    2. If you don't Dispose() the CancellationTokenRegistration returned from Register(), and the CancellationTokenSource is long-lived, you have a memory leak, since the registrations will stay in memory as long as the CancellationTokenSource.

    Depending on your requirements, and your desire for clean code (even at the cost of complexity) it may be okay to ignore problem #2 and work around problem #1 by swallowing the exception in a catch.

    0 讨论(0)
提交回复
热议问题