Undo the topic started with the delegate .BeginInvoke

Disclaimer : I know that Thread.Abort is evil. I use it as a last resort, because some I / O functions (for example, File.Exists when used in a non-existent network resource) are blocked for a long time and do not allow to specify a timeout.

Question : is it possible to interrupt (as in Thread.Abort ) a workflow started using Delegate.BeginInvoke , or do I need to process Thread myself?

+4
source share
2 answers

The only way to do this is to let the delegate pass its Thread.CurrentThread to the main thread.

However, you should not do this; terminating ThreadPool threads is not a good idea. (If you do not cancel the cancel in the catch )

You will need to use your own threads.

+2
source

It would be dangerous to call Abort on the thread method that occurs in the delegate called with Delegate.BeginInvoke.

Delegate.BeginInvoke launches a delegate in the ThreadPool thread. Terminating a ThreadPool thread through Abort can lead to very strange errors, since ThreadPool is not designed to handle this.

This, as they say, is also completely unnecessary. You should always be able to detect from the ThreadPool thread whether you want to abort and simply return accordingly. If a ThreadPool thread is blocked, this will not be a problem either, since it does not block your main thread. It would be better to just check after your blocking call (i.e., immediately after File.Exists ) and just return if you want to refuse at this time.

+3
source

Source: https://habr.com/ru/post/1299970/


All Articles