这是我的task
课程:
public class QueueTask
{
private ManualResetEvent _doneEvent;
Queue<QueueObject> _queu;
public QueueTask(ManualResetEvent doneEvent, Queue<QueueObject> queu)
{
this._doneEvent = doneEvent;
_queu = queu;
}
public void ThreadPoolCallback(Object threadContext)
{
int threadIndex = (int)threadContext;
Console.WriteLine("Thread {0} was started...", threadIndex);
QueueObject element = _queu.Dequeue();
int id = DoSomeLongOperation(element);
Console.WriteLine("Thread {0} was finished... queueObjectID: {1}", threadIndex, id);
_doneEvent.Set();
}
protected virtual int DoSomeLongOperation(QueueObject obj)
{
Random rand = new Random();
Thread.Sleep(rand.Next(5000, 10000));
return obj.ID;
}
}
这就是我称之为线程池的地方:
public static void RunThreadPull(Queue<QueueObject> queue, int batchSize)
{
ManualResetEvent[] doneEvents = new ManualResetEvent[batchSize];
Console.WriteLine("Running batch which consist of 6 objects...");
for (int j = 0; j < batchSize; j++)
{
doneEvents[j] = new ManualResetEvent(false);
QueueTask task = new QueueTask(doneEvents[j], queue);
WaitCallback callback = new WaitCallback(task.ThreadPoolCallback);
ThreadPool.QueueUserWorkItem(callback, j);
}
WaitHandle.WaitAll(doneEvents);
Console.WriteLine("All calculations in current batch were completed!");
}
我需要在线程拉取中为每个线程设置超时。我需要停止线程并执行另一个操作。不知道究竟是什么动作,让它成为方法TimeoutExpiredAction()
。有没有办法做到这一点?