Timeout for a method on the UI thread

I have a problem that I am running an object on a UI thread (WinForms). This object is probably taking a very long time to create and I would like to have some kind of "timeout" for this method (since it blocks my application).

I have problems: 1. the object must be created on the UI thread 2. the object is a foreign object and I don't have any access to the source, so I cannot change it.

So the question would be, if anyone has a creative idea if it is possible to create logic that stops a method from being executed if the timeout is reached?

TIA Martin

+1


source to share


3 answers


Here's a bad solution. Use a worker thread on a timer to monitor the UI thread. If the timer expires before the object is created, ask for a workflow thread Abort

on the UI thread. This will cause an increase ThreadAbortException

in the UI thread that you should catch. The reasons this is bad is because you can damage or crash your program depending on the delicate timing and race conditions when the exception is thrown.



The "safer" method is that a worker call Interrupt

- this will cause an increase ThreadInterruptedException

in the UI thread, but only when it is in a state WaitSleepJoin

- if the thread never sleeps, it won't interrupt, but at least it won't hang and will not spoil the memory.

+1


source


Not really; especially if you don't have access to the source.

Even if you could, it is not a good idea to force abort the code for no good reason - it can only lead to problems (leaks, locks remain locked, etc.).



Should there be the same UI thread? Could you create a second UI thread to own this code? It gets a little patchy, but it can work.

0


source


if you are using BeginInvoke, IAsyncResult has a wait handle, by which you can WaitOne (timeout) - from -UI.

Unfortunately there is no clean way to undo this BeginInvoke on timeout, so you can try the 1800 INFORMATION

solution.

0


source







All Articles