Is it possible to kill the BackgroundWorker's thread?

*爱你&永不变心* 提交于 2019-12-01 16:44:01

问题


Is it possible "kill" the thread of a BackgroundWorker?

In my DoWork event, I can't check the cancellation flag, because I have a blocking call to an external COM interface or a query to a database. CancelAsync doesn't cancel the call to COM.

How can I do it, please ? Any suggestions will be very appreciated.

Thanks in advance.


回答1:


I'm not aware of a safe way to abort a thread.

A background worker can check if it should cancel and cancel itself, but if it's off querying a database there's not much you can do until it returns.

You can do work on a ThreadPool thread and just abandon the thread and start another if it's not needed anymore (making sure that when it comes back from a db query it checks if it should cancel before doing anything nasty). Of course you'd need to balance the performance and manage thread synchronisation. If you go down that path, you could take a look at the Interlocked static class for efficient critical section locking.




回答2:


No, you can't kill the BackgroundWorker thread, you can only try to cancel it as you noticed, but it requires some interaction from the background thread itself to stop the work: "The worker code should periodically check the CancellationPending property to see if it has been set to true." (c) MSDN

If you need full control over a thread, you will have to create it by yourself using Thread class.



来源:https://stackoverflow.com/questions/543811/is-it-possible-to-kill-the-backgroundworkers-thread

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