当ConcurrentQueue包含太多项时,工作线程阻塞

时间:2017-01-05 15:47:45

标签: c# multithreading winforms thread-safety concurrent-queue

这是一个奇怪的问题,我有一个Thread[]工作线程,每个工作线程处理ConcurrentQueue<string>中的项目,直到队列为空,此时程序的其余部分继续。

直到大约1500个项目才有效,此时所有线程都在WaitSleepJoin状态下被阻止,并且永远不会处理队列中的任何项目。

我已经尝试逐步执行我的代码,看起来线程仍在创建,仍然启动并且仍处于活动状态,但会立即被阻止,并且永远不会运行相关功能。

我完全陷入困境,所以任何帮助都会受到赞赏!

相关的代码部分如下:

主线程段:

            ConcurrentQueue<string> convertionQueue = new ConcurrentQueue<string>();
            List<Thread> converterThreads = new List<Thread>();
            Directory.GetFiles(_folderOne, "*.fdf", SearchOption.AllDirectories).ToList().ForEach(file => convertionQueue.Enqueue(file));
            Directory.GetFiles(_folderTwo, "*.fdf", SearchOption.AllDirectories).ToList().ForEach(file => convertionQueue.Enqueue(file));
            int filesDone = 0;
            int totalFiles = convertionQueue.Count;
            progressBar.Maximum = totalFiles;
            panel1.Visible = true;
            for (int i = 0; i < Environment.ProcessorCount; i++)
            {
                converterThreads.Add(new Thread(() => ConvThreadWorker(convertionQueue, ref filesDone)));
            }
            converterThreads.ForEach(thread => thread.Start());
            DateTime lastTick = DateTime.Now;
            int lastFilesDone = 0;
            int[] valuesSpeed = { 1, 1, 1, 1, 1 };
            int[] valuesTime = { 1, 1, 1, 1, 1 };
            int counter = 0;
            while (converterThreads.Any(thread => thread.IsAlive))
            {

                TimeSpan t = DateTime.Now - lastTick;
                int deltaFiles = filesDone - lastFilesDone;
                double speed = (float)t.TotalMilliseconds <= 0.0 ? 0.0 : deltaFiles / (float)t.TotalMilliseconds;
                double tMinus = speed <= 0 ? 0.0 : (totalFiles - filesDone) / speed;
                int currentSpeed = (int)(speed * 1000);
                int currentTime = (int)(tMinus / 1000);
                valuesSpeed[counter] = currentSpeed;
                valuesTime[counter] = currentTime;
                lblFilesLeft.Text = string.Format("{0}/{1}", filesDone, totalFiles);
                lblSpeed.Text = valuesSpeed.Sum() / 5 + " /s";
                lblTime.Text = valuesTime.Sum() / 5 + " s";
                lblFilesLeft.Update();
                lblSpeed.Update();
                lblTime.Update();
                progressBar.Value = filesDone;
                progressBar.Update();
                lastTick = DateTime.Now;
                lastFilesDone = filesDone;
                counter = ++counter % 5;
                Thread.Sleep(500);
            }

工作人员职能:

private void ConvThreadWorker(ConcurrentQueue<string> queue, ref int fileCounter)
{
    while (!queue.IsEmpty)
    {
        string file;
        if (queue.TryDequeue(out file))
        {
            ConvToG(file);
            fileCounter++;
        }
    }
}

转换功能:

private void ConvToG(string file)
{
    MessageBox.Show("Entering Convertion Function");
    if (!_fileCreationDictionary.ContainsKey(file))
    {
        DateTime lastTimeModified = File.GetLastWriteTime(file);
       _fileCreationDictionary.AddOrUpdate(file, lastTimeModified, (key,oldvalue)=>lastTimeModified);
    }
    ProcessStartInfo procStart = new ProcessStartInfo
    {
        Arguments = file,
        UseShellExecute = true,
        FileName = Fdfg,
        WindowStyle = ProcessWindowStyle.Hidden
    };
    Process process = new Process {StartInfo = procStart};
    MessageBox.Show("Starting convertion process");
    process.Start();
    process.WaitForExit();
    MessageBox.Show("Finished");
}

令人困惑的部分似乎是这一切都围绕着队列中的项目数量,但似乎没有溢出。

更新:添加mbox会显示它冻结在代码的process.Start()部分,没有错误,也不会超过该点。

更新2:如果UseShellExecute = false代码有效。至少可以说这是非常令人困惑的。

1 个答案:

答案 0 :(得分:1)

我做了一些与线程生成过程类似的东西来整理数据。我有关于实际过程开始和悬挂的问题。我为使我的程序工作所做的是这样的:

using (Process process = Process.Start(startInfo)) {
    if(process.WaitForExit(timeOutMilliseconds)) {
        MessageBox.Show("Process exited ok");
        //...snip
    } else {
        MessageBox.Show("Process did not exit in time!");
        //...snip
        process.Kill();
    }
}

在后台还有更多关于限制正在运行的进程的数量等等,但我偶尔发现,由于一个未知的原因,我会在任务管理器中看到几个永远存在的进程。

希望有帮助吗?

相关问题