Featured post
c# - Terminate a thread after an interval if not returned -
i have thread grabs data network or serial port. thread must terminate (or return false) if no data received within 5 seconds.
in other words, if running thread taking more 5 seconds must stop.
i writing in c#, .net language ok.
there 2 approaches:
1. encapsulated timeout
the thread reading data network or serial port can measure time elapsed time of start , wait data no more remaining time. network communication apis provide means specify timeout operation. hence doing simple datetime
arithmetic can encapsulate timeout management within worker thread.
2. external timeout
use thread (or in main thread if that's feasible) wait worker thread finish within time limit, , if not, abort it. this:
// start worker thread ... // give no more 5 seconds execute if (!workerthread.join(new timespan(0, 0, 5))) { workerthread.abort(); }
recommendation: i'd stick first solution, leads cleaner , maintainable design. however, in situation might necessary provide means 'hard' abort of such worker threads.
- Get link
- X
- Other Apps
Comments
Post a Comment