Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terminate a thread after an interval if not returned

I have a thread which grabs some data from network or serial port. The thread must terminate (or return false) if no data is received within 5 seconds.

In other words, if running the thread is taking more than 5 seconds it must stop.

I am writing in C#, but any .NET language is OK.

like image 508
Mahdi Avatar asked Dec 21 '10 16:12

Mahdi


1 Answers

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 execute
if (!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.

like image 158
Ondrej Tucny Avatar answered Sep 29 '22 12:09

Ondrej Tucny