【发布时间】:2017-09-08 13:03:55
【问题描述】:
我正在做一个项目,该项目需要读取二维码,将其排队,因为它正在排队另一个任务,将数据出列并通过套接字消息将其发送到机器。这都是在 c# 中完成的。
我的问题是如何在另一个任务出队时保持队列。我有二维码工作,我可以排队和出队,套接字消息传递部分工作。但我不知道如何同时运行队列和出队。
我研究过线程,特别是多线程。我比开始阅读之前更加困惑。
任何帮助将不胜感激。
编辑:所以根据你们的 cmets 和做一些研究,我开始编写一些代码。不管我做什么,线程只运行一次。它应该继续运行。
public partial class Form1 : Form
{
private BlockingCollection<string> _queue = new BlockingCollection<string>(30);
//private string item = "A";
//private int count = 0;
private Thread _th1;
public Form1()
{
InitializeComponent();
_th1 = new Thread(thread_example);
_th1.Start();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void thread_example()
{
if (_queue.Count > 0)
{
_queue.Take();
Console.WriteLine("Removed 1 Item from queue!");
}
else
{
Console.WriteLine("Queue Empty!");
}
Thread.Sleep(500);
}
private void btnProduce_Click(object sender, EventArgs e)
{
_queue.Add("test_string");
Console.WriteLine("Added 1 item to the queue");
}
}
【问题讨论】:
-
“线程只运行一次。它应该继续运行”——如果是这样,你为什么不做任何事情让它保持运行?比如,包含一个循环以允许线程继续运行?坦率地说,你的问题太宽泛了......很明显,你真正需要的是自己做一些研究,了解 C# 中的生产者/消费者模式,以及线程同步技术,让消费者无需等待新数据消耗CPU时间。
BlockingCollection类可能是您在这里的最佳选择,但没有任何方法可以确定,因为问题如此广泛。 -
在您的示例中,您有一个
thread_example方法,该方法仅被调用一次,然后线程退出。如果您希望消费者通过_queue.Take()持续消费,那么您需要在thread_example中使用某种类型的无限循环,它会调用_queue.Take()。您的代码也破坏了阻止功能。你的代码应该是private void thread_example() { while (true) { _queue.Take(); Console.WriteLine("Removed 1 Item from queue!"); } } -
顺便说一句,如果您想通过跟进通知我,您必须对我的回答发表评论以引起我的注意。另外,如果我的回答对你有用,那么你应该点赞并接受它
标签: c# multithreading parallel-processing queue multitasking