It's often the case when I need to get a task done within X amount of seconds and if it doesn't complete, I want to keep going, processing the rest of the tasks
I've been defaulting to something like this:
Thread worker = new Thread(() => {
// do some long operation
});
Thread monitor = new Thread(() => {
Thread.Sleep(10000);
if(worker != null && worker.IsAlive) {
worker.Abort();
worker = null;
}
StartNextTask();
});
monitor.Start ();
worker.Start();
This works, but it is cumbersome because it uses two threads (yes, you can use the Task
class as well to use threads from the threadpool).
AutoResetEvent
s and event
based models don't quite work because the former blocks the monitor thread until the worker is done, and the event
driven approach relies on the client to call the event and notify the monitor.
Are there alternative patterns to this that can follow the same semantics?