How to Cancel a Thread?

前端 未结 4 2034
旧巷少年郎
旧巷少年郎 2020-12-06 13:18

In case of BackgroundWorker, a cancel can be reported by the e.Cancel - property of the DoWork - event handler.

How can I achieve the same

4条回答
  •  旧巷少年郎
    2020-12-06 14:02

    There's Thread.Abort, which works by injecting a ThreadAbortException into the thread. It's a little risky because:

    1. Your thread can get stuck if it's executing native code at the time
    2. The code in the thread better be exception-safe, because this ThreadAbortException could happen on any line of code within it, even something innocent like i = i + 1

    You're better off coding your own signalling mechanism between your GUI thread and the background thread. It's hard to recommend something without knowing what's going on inside that thread, but where I have a thread that works by waiting on some object in a loop, I use an AutoResetEvent and wait on that too.

提交回复
热议问题