本文介绍了为什么消费者按顺序而不是同时运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个生产者和四个消费者。我想要四个消费者同时处理来自生产者的物品。但事实并非如此。它是顺序的。
我把所有代码放在这里。感谢您的帮助。
I have one producer and four consumers. I want four consumers process items from the producer concurrently. However, it is not. It is sequentially instead.
I put all code here. Thanks for help.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConcurrentMakeTest
{
class Program
{
public static BlockingCollection<string> m_Queue =
new BlockingCollection<string>();
public static Object obj = new Object();
static void Main(string[] args)
{
Task producer = Task.Run(() => Producer());
Task consumer1 = Consumer();
Task consumer2 = Consumer();
Task consumer3 = Consumer();
Task consumer4 = Consumer();
Task.WaitAll(producer, consumer1, consumer2, consumer3, consumer4);
Console.WriteLine("-----------------------------------------");
Console.ReadLine();
}
static void Producer()
{
try
{
for (int i = 0; i <= 10; i++)
{
m_Queue.TryAdd(i.ToString());
}
}
finally
{
m_Queue.CompleteAdding();
Console.WriteLine("There are totally {0} items in the queue.\n", m_Queue.Count);
Thread.Sleep(500);
}
}
static async Task Consumer()
{
try
{
while (m_Queue.Count > 0)
{
string x = "";
m_Queue.TryTake(out x);
await Task.Factory.StartNew(() =>
{
lock (obj)
{
PrintItem m = new PrintItem(DateTime.Now);
m.RunScript(x);
}
});
}
}
catch (Exception ex)
{
Console.Write("Exception: " + ex.Message + "\r\n" + ex.StackTrace);
}
}
}
}
和:
And:
public class PrintItem
{
public PrintItem(DateTime t)
{
Console.WriteLine(t);
}
internal void RunScript(string item)
{
Console.WriteLine(item);
}
}
推荐答案
这篇关于为什么消费者按顺序而不是同时运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!