BlockingCollection多线程Producer Consumer

时间:2014-08-29 06:43:50

标签: c# .net multithreading producer-consumer

我想实现多线程Producer Consumer,我的目的是在我的Queue中插入字符串,每个字符串代表需要检查的DOC file(在文档中进行简单搜索)并且在此检查中是好的,doc文件可以添加到我的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);
        }
    }
}

现在我想在我的类中添加在多个线程中添加文件的选项。 有任何建议怎么做?

0 个答案:

没有答案