Terminate a thread after an interval if not returned Terminate a thread after an interval if not returned multithreading multithreading

Terminate a thread after an interval if not returned


There are two approaches:

1. Encapsulated timeout

The thread reading the data from network or serial port can measure time elapsed from its time of start and wait for the data for no more than the remaining time. Network communication APIs usually provide means to specify a timeout for the operation. Hence by doing simple DateTime arithmetic you can encapsulate timeout management within your worker thread.

2. External timeout

Use another thread (or do it in the main thread if that's feasible) to wait for the worker thread to finish within a certain time limit, and if not, abort it. Like this:

// start the worker thread...// give it no more than 5 seconds to executeif (!workerThread.Join(new TimeSpan(0, 0, 5))){        workerThread.Abort();}

Recommendation: I'd stick with the first solution, as it leads to cleaner and maintainable design. However, in certain situation it might be necessary to provide means for 'hard' abort of such worker threads.


Either mechanism should allow you to specify a timeout on the read. For example, you could set NetworkStream.ReadTimeout to 5000 before performing the read. You should be able to do something similar for serial ports.

A read that has timed out will return 0 from Stream.Read() -- this is how you can tell if a timeout actually occurred.

Note that using Thread.Abort() is deprecated as of .NET 2.0 for some serious problems it can cause. You could theoretically use Thread.Interrupt(), but this will not do anything when the thread is blocked in unmanaged code (including I/O). Using read timeouts is the proper way to solve this problem.


If you are using managed code to block the thread, you can use Thread.Abort to abort the execution. If you are using 3rd party code or COM interop, there is no way of terminating the thread execution. The only way is setting the Thread.isBackroundThread to true, and then terminating the Process...