我有一个Windows 服务,可以进行一些图像转换.它可以在重命名任何文件(在特定文件夹中)时触发(即重命名文件观察者).工作得很好,直到我在该文件夹中转储(和重命名)大量图像.CPU红线等.
所以,我打算更改我的代码以使用MSMQ排队所有需要转换的文件.精细.每次重命名文件并触发文件监视器时,我都会向队列中添加一条新消息.KEWL.
问题是这个 - > 我如何从队列中一次抓取一条消息?
我是否需要制作一个每隔xxx秒轮询一次队列的计时器对象?或者有没有办法不断窥视队列中的第一个项目.一旦消息存在,提取它,处理它,然后继续(这意味着,继续偷看,直到世界爆炸).
我想知道我是否只需要在Receive方法周围放置一个while循环.Pseduo代码如下(在编辑#2中)......
任何人都有这方面的经验并有一些建议吗?
谢天谢地!
如果WCF是要走的路,有人可以提供一些示例代码等吗?
这是我正在考虑的一些伪代码....
// Windows service start method.
protected override void OnStart(string[] args)
{
// some initialisation stuf...
// Start polling the queue.
StartPollingMSMQ();
// ....
}
private static void StartPollingMSMQ()
{
// NOTE: This code should check if the queue exists, instead of just assuming it does.
// Left out for berevity.
MessageQueue messageQueue = new MessageQueue(".\\Foo");
while (true)
{
// This blocks/hangs here until a message is received.
Message message = messageQueue.Receive(new TimeSpan(0, 0, 1));
// Woot! we have something.. now process it...
DoStuffWithMessage(message);
// Now repeat for eva and eva and boomski...
}
}
Run Code Online (Sandbox Code Playgroud)
小智 26
如果使用本地队列,则不需要WCF.
这是我的示例服务(来自Windows服务项目的服务clas)的样子:
using System.Messaging;
public partial class MQProcessTest1 : ServiceBase
{
//a name of the queue
private const string MqName = @".\Private$\test1";
//define static local private queue
private static MessageQueue _mq;
//lazy local property through which we access queue (it initializes queue when needed)
private static MessageQueue mq
{
get
{
if (_mq == null)
{
if (!MessageQueue.Exists(MqName))
MessageQueue.Create(MqName);
_mq = new MessageQueue(MqName, QueueAccessMode.ReceiveAndAdmin);
_mq.Formatter = new BinaryMessageFormatter();
}
return _mq;
}
}
//constructor
public MQProcessTest1()
{
InitializeComponent();
//event to process received message
mq.ReceiveCompleted += new ReceiveCompletedEventHandler(mq_ReceiveCompleted);
}
//method to process message
private void mq_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
{
//queue that have received a message
MessageQueue cmq = (MessageQueue)sender;
try
{
//a message we have received (it is already removed from queue)
Message msg = cmq.EndReceive(e.AsyncResult);
//here you can process a message
}
catch
{
}
//refresh queue just in case any changes occurred (optional)
cmq.Refresh();
//tell MessageQueue to receive next message when it arrives
cmq.BeginReceive();
}
protected override void OnStart(string[] args)
{
//let start receive a message (when arrives)
if (mq != null)
mq.BeginReceive();
//you can do any additional logic if mq == null
}
protected override void OnStop()
{
//close MessageQueue on service stop
if (mq != null)
mq.Close();
return;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14340 次 |
| 最近记录: |