Stopping work from one thread using another thread

后端 未结 2 630
南笙
南笙 2021-01-21 19:03

Not sure if my title is worded well, but whatever :)

I have two threads: the main thread with the work that needs to be done, and a worker thread that contains a form wi

2条回答
  •  鱼传尺愫
    2021-01-21 20:06

    I recommend using CancellationTokenSource, which can handle this kind of complex scenario. It's part of the Task Parallel Library but does not actually have to be used with Task objects; it can just as easily be used with old-style Thread objects.

    Of course, if you have the time, I'd recommend defining the main thread's work as a Task object (running on the main UI thread by using TaskScheduler.FromCurrentSynchronizationContext).

    Note that everything above assumes .NET 4.0. If you're still stuck on the old platform, you'll just have to have a bool cancelled; field protected by a lock or some such thing. Tip: don't call Thread.Abort; it's evil.

提交回复
热议问题