我正在尝试通过引入线程来提高应用程序的性能(请参阅我的earlier问题)。我已经用XML消息填充了一个Queue(of String),现在我想设置两个线程将这些消息发布到web服务器上。此过程需要确保每条消息仅发布一次。 BackgroundWorker(或两个)是否适合这个?
我不知道从哪里开始,我看过的一些样本没有多大意义!任何帮助都感激不尽。
答案 0 :(得分:2)
using System;
using System.Collections.Generic;
using System.Threading;
namespace QueueTest
{
class QueueTest
{
[STAThread]
static void Main(string[] args)
{
QueueTest d = new QueueTest();
d.Run();
}
Queue<string> m_Queue=new Queue<string>();
QueueTest()
{
for (int i = 0; i < 10000; i++)
{
m_Queue.Enqueue("Message " + i);
}
}
private void Run()
{
//Create and start threads
Thread t1 = new Thread(new ThreadStart(QueueReader));
Thread t2 = new Thread(new ThreadStart(QueueReader));
t1.Start();
t2.Start();
t1.Join();
t2.Join();
}
//Thread function
private void QueueReader()
{
while (true)
{
string msg = null;
lock (m_Queue)
{
if (m_Queue.Count > 0)
msg = m_Queue.Dequeue();
else
{
return;
//whatever you want to do when a queue is empty, for instance
//sleep or exit or wait for event.
//but you have to do something here to avoid empty loop with 100% CPU load
Thread.Sleep(1000);
}
}
//this is where you post your message
//it's important to do this outside lock()
if (msg != null) ProcessMessage(msg);
}
}
private void ProcessMessage(string msg)
{
Console.WriteLine(msg);
Thread.Sleep(500);
}
}
}
答案 1 :(得分:0)
此外,您可以使用名为Parallel Extensions Framework的http://blogs.msdn.com/pfxteam/库中的ConcurrentQueue<T>
。