0

i want to implement multiple thread Producer Consumer, my purpose is insert strings into my Queue, each string represent DOC file that need to be check (simple search inside the document) and in this check is OK the doc file can be add into my ListView.

public class ProducerConsumer
{
    public delegate void OnFileAddDelegate(string file);
    public event OnFileAddDelegate OnFileAddEventHandler;
    private BlockingCollection<string> queue = new BlockingCollection<string>();

    public void Start(int workerCount)
    {
        int count = 0;
        while (count < workerCount)
        {
            Thread thread = new Thread(StartConsuming);
            thread.IsBackground = true;
            thread.Start();
            count++;
        }
    }

    public void Produce(string item)
    {
        queue.Add(item);
    }

    private void StartConsuming()
    {
        while (queue.Count > 0)
        {
            string item = queue.Take();

            // Check my file
            FileChecker fileChecker = new FileChecker();
            string result = fileChecker.Check(item); 

            // If the file is OK fire up an event to my main form to add this file
            if (result != null && OnFileAddEventHandler != null)
                OnFileAddEventHandler(result);
        }
    }
}

Now i want add to my class the option to add files in multiple thread. Any suggestions how to do that ?

may danit
  • 25
  • 6
  • 1
    I don't understand what is the problem or what the question is? – Sriram Sakthivel Aug 29 '14 at 06:46
  • Is my Consumer is multiple thread ? – may danit Aug 29 '14 at 06:50
  • If you ask multiple threads are processing the work items(consumers) **no**, you have only one consumer created in `Start` method. Of course **yes** if you call `Start` method multiple times. – Sriram Sakthivel Aug 29 '14 at 06:52
  • What i need to change in order to support multiple threads ? i don't think call Start multiple times is a good idea (correct me if i wrong) – may danit Aug 29 '14 at 07:04
  • Calling start multiple times is worst idea. But you could add parameter to `Start` method lets say `public void Start(int workerCount)` then start that many number of threads inside `Start` method. You're done. – Sriram Sakthivel Aug 29 '14 at 07:06
  • Please see my update, that's what you mean ? – may danit Aug 29 '14 at 07:17
  • Yes, exactly. If you have used `for` loop it would be better. but that's fine. Now you can start multiple consumers. Also see [this](http://www.albahari.com/threading/part5.aspx), In that page search for `PCQueue`. You'll find a better implementation of producer consumer. – Sriram Sakthivel Aug 29 '14 at 07:22

0 Answers0