views:

397

answers:

2

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  A: 

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.

SLaks
Note that catching the abort isn't enough; it gets rethrown automatically. Yes, there's a way around this, but it's better to follow your advice and avoid the issue entirely. Thread.Abort is evil.
Steven Sudit
@Steven: Yes; I forgot to mention ResetAbort.
SLaks
+2  A: 

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.

Reed Copsey