If you don't want to block the main thread you can use a System.Threading.Timer:
private Thread _thread;
void Main(string[] args)
{
_thread = new ThreadStart(ThreadEntry);
_thread.Start();
Timer timer = new Timer(Timeout,null,30000,Timeout.Infinite);
}
void ThreadEntry()
{
int result = obj.PerformInitTransaction();
}
void TimeOut(object state)
{
// Abort the thread - see the comments
_thread.Abort();
throw new ItTimedOutException();
}
Jon Skeet has a less forceful way (Shutting Down Worker Threads Gracefully) of stopping the thread than abort.
However as you're not in control of the operations PerformInitTransaction()
is doing there is not much you can do from when Abort fails and leaves the object in an invalid state. As mentioned if you are able to cleanup anything that aborting the PerformInitTransaction
has left hanging, you can do this by catching the ThreadAbortException
, though as it's a 3rd party call it'll mean guessing the state you've left their method in.
The PerformInitTransaction
should really be the one providing the timeout.