0

I am in the middle of the windows service multithread project where I need some inputs from you guys to run it successfully. below is the code and describe what I am trying to do and problem.

// I created a new thread and call MyTimerMethod() from the Main method.
private void MyTimerMethod()
{
    timer = Timers.Timer(5000)
    timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
    timer.Start();

    // make this thread run every time.
    Application.Run(); 
}

private void OnElapsedTime(object source, ElapsedEventArgs e)
{
    for(int i = 0; i < SomeNum; i++) //SomeNum > 0    
    ThreadPool.QueueUserWorkItem(WaitCallback(MyWorkingMethod),null);
}

private void MyWorkingMethod(object state)
{
    // each thread needs to go and check the status and print if currentStatus = true.
    // if currentStautus = true then that jobs is ready to print.
    // FYI ReadStatusFromDB() from the base class so I cannot modify it.

     ReadStatusFromDB(); // ReadStatusFromDB() contains jobs to be printed.
    // after doing some work store procedure update the currentStatus = false. 

    //do more stuff.
}

Long story in short, program runs every five seconds and check if there is more work to do. If there is then create a new thread from the threadpool and push into the queue. Now my problem is when there is more than one threads in the queue. Even the currentStatus = false multiple threads grab the same jobs and tries to print.

let me know if you need further information.

1 Answer 1

0

I would suggest creating a BlockingCollection of work items, and structure your program as a producer/consumer application. When a job is submitted (either by the timer tick, or perhaps some other way), it's just added to the collection.

You then have one or more persistent threads that are waiting on the collection with a TryTake. When an item is added to the collection, one of those waiting threads will get and process it.

This structure has several advantages. First, it prevents multiple threads from working on the same item. Second, it limits the number of threads that will be processing items concurrently. Third, the threads are doing non-busy waits on the collection, meaning that they're not consuming CPU resources. The only drawback is that you have multiple persistent threads. But if you're processing items most of the time anyway, then the persistent threads isn't a problem at all.

1
  • Thank you so much for your input. I am completely new to this technology I want to modify this code instead of writing the new code.
    – Lakhae
    Oct 16, 2012 at 17:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.