Abort a Thread started with Delegate.BeginInvoke

2019-05-03 17:37发布

Disclaimer: I know that Thread.Abort is evil. I'm using it as a last resort since some I/O functions (e.g., File.Exists when used on a non-existing network share) block for a large amout of time and do not allow you to specify a timeout.

Question: Is it possible to Abort (as in Thread.Abort) a worker thread started using Delegate.BeginInvoke or do I have to do the Thread handling myself?

2条回答
男人必须洒脱
2楼-- · 2019-05-03 18:04

It would be dangerous to call Abort on the thread method that's occurring within a delegate called with Delegate.BeginInvoke.

Delegate.BeginInvoke fires up the delegate on a ThreadPool thread. Terminating the ThreadPool thread via Abort could cause very odd bugs to creep in, since the ThreadPool is not intended to handle this.

That being said, it's also completely unnecessary. You should always be able to detect, from within the ThreadPool thread, whether you want to abort, and just return appropriately. If the ThreadPool thread is being blocked, that also will not really be an issue, since it's not blocking your main thread. It'd be better to just put a check after your blocking call (ie: right after File.Exists), and just return if you want to abort at that time.

查看更多
Bombasti
3楼-- · 2019-05-03 18:06

The only way to do that would be to have the delegate pass its Thread.CurrentThread to the main thread.

However, you should not do it; terminating ThreadPool threads is not a good idea. (Unless you cancel the abort in a catch block)

You'll have to use your own threads.

查看更多
登录 后发表回答