Cancel ThreadPool .QueueUserWorkItem Task

前端 未结 1 1257
没有蜡笔的小新
没有蜡笔的小新 2021-01-22 01:55

I need to cancel a background task started using ThreadPool.QueueUserWorkItem(...). I know a BackgroundWorker has constructs especially for this sort of thing, but I believe it\

相关标签:
1条回答
  • 2021-01-22 02:51

    I'd use a method CancelTask() rather than a property. The point is that callers should be able to cancel a task, but no one should be able to un-cancel a task.

    Then you need to be sure that the read and the write of _cancelled have the appropriate memory barriers otherwise one thread might not ever observe the change made by the other thread. For this I'd use Thread.VolatileWrite (inside CancelTask) and Thread.VolatileRead (inside your loop)

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