0

This is my task class:

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;
    }
}

And this is where I call thread pool:

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!");   
}

I need to set timeout to each thread in thread pull. I need to Stop thread and do another action. Don't know what action exactly, let it be method TimeoutExpiredAction(). Is exist any way to do that?

H H
  • 263,252
  • 30
  • 330
  • 514
Alexander
  • 691
  • 1
  • 11
  • 29

0 Answers0