1

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).

AutoResetEvents 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?

4

1 回答 1

2

如果您按照您所说的那样使用 Task 类,您还可以使用 Task.Wait() ,它完全符合您的要求。指定等待的秒数。除非您使用 CancellationToken 取消任务,否则该任务不会被取消

请参阅:http: //msdn.microsoft.com/en-us/library/dd235606.aspx

于 2012-12-11T16:00:00.613 回答