Abort a Thread started with Delegate.BeginInvoke
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?
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.
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.
精彩评论