简体   繁体   中英

Abort a Thread started with Delegate.BeginInvoke

: I know that Thread.Abort is evil. :我知道Thread.Abort是邪恶的。 I'm using it as a last resort since some I/O functions (eg, 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.

: 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? :是否可以使用Delegate.BeginInvoke中止工作线程(如在Thread.Abort ),或者我是否必须自己进行线程处理?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM