views:

83

answers:

3

Hi,

I have the problem that I'm instanciating an object on the UI-thread (WinForms). This object creation probably takes very long, and I would like to have some sort of a "timeout" for that method (because it's blocking my app).

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

So me question would be, if somebody has a creative idea, if it is possible to create a logic which stops the method for been executed if a timeout is reached?

tia Martin

+1  A: 

Here is a bad solution. Use a worker thread on a timer to monitor the UI thread. If the timer elapses before the object is created, have the worker thread call Abort on the UI thread. This will raise a ThreadAbortException in the UI thread which you must catch. The reasons why this is bad is because you can cause your program to hang or crash depending on subtle timing and race conditions for when the exception is raised.

A "safer" method is to have the worker call Interrupt - this will raise a ThreadInterruptedException in the UI thread, but only when it is in the WaitSleepJoin state - if the thread never sleeps it will not interrupt, but at least it won't hang or corrupt memory either.

1800 INFORMATION
A: 

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

Even if you could, it isn't a good idea to forcibly interrupt code without good reason - it can only lead to problems (leaks, locks being left locked, etc).

Does it have to be the same UI thread? You could spawn a second UI thread to own this code? It gets a little scrappy, but can work.

Marc Gravell
A: 

if you're using BeginInvoke, the IAsyncResult has a wait handle on which you can WaitOne(timeout) - from the non-UI thread.

Unfortunately, on timeout, there is no clean way to cancel that BeginInvoke - so you may try 1800 INFORMATION's solution.

Vlagged