How can I stop async Process by CancellationToken?

两盒软妹~` 提交于 2019-12-05 14:29:51

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!