我首先要说的是我不是.NET开发人员,但是我已经被投入到需要使用MSMQ的项目中,所以经典的ASP Web应用程序可以将消息发送到处理处理的C#Windows服务。我有将其他消息队列与其他语言集成的经验,但正如我所提到的,我对.NET和Windows开发没有太多经验,因此我们非常感谢一些指导。
以下是我的问题......
有人可以提供一些基本的C#代码来监听现有的MSMQ队列并通过执行一些简单的操作来响应新消息,例如将当前时间戳写入日志文件或发送电子邮件吗?
如何在Visual Studio .NET中打包此代码以创建和安装Windows服务? (它应该是什么类型的项目,等等。我正在使用Visual C#2010 Express。)
最后,我不确定我需要使用哪种版本和/或MSMQ实现来满足我对经典ASP的要求。我认为COM版本是我需要的,但我也读过一个新的WCF版本,以及3.0和4.0之间的差异。有人可以告诉我我应该使用哪个版本的方向吗?
非常感谢!
答案 0 :(得分:8)
您可以使用以下代码等待给定队列上的消息(您希望在计算机上使用名为SomeQueue的专用队列,名为ComputerName => QueueName = @“ComputerName \ private $ \ SomeQueue”)
public void AsyncWatchQueue(object encapsulatedQueueName)
{
Message newMessage;
MessageQueue queue;
string queueName = encapsulatedQueueName as string;
if (queueName == null)
return;
try
{
if (!MessageQueue.Exists(queueName))
MessageQueue.Create(queueName);
else
{
queue = new MessageQueue(queueName);
if (queue.CanRead)
newMessage = queue.Receive();
}
HandleNewMessage(newMessage); // Do something with the message
}
// This exception is raised when the Abort method
// (in the thread's instance) is called
catch (ThreadAbortException e)
{
//Do thread shutdown
}
finally
{
queue.Dispose();
}
}
注意:Receove方法将阻止直到收到一条消息,此时它将从队列中删除消息并将其返回。
编辑:为多线程部分的实现添加了代码(并重命名了上述方法签名)
线程创建代码:
public Thread AddWatchingThread(string QueueName)
{
Thread Watcher =
new Thread(new ParameterizedThreadStart(AsyncWatchQueue));
Watcher.Start(QueueName);
// The thread instance is used to manipulate (or shutdown the thread)
return Watcher;
}
我要注意,这是未经测试的鳕鱼,它只是一个简单的例子
答案 1 :(得分:3)
据我所知,Visual Studio Express没有服务的项目模板。这并不意味着您无法使用VSE编写Windows服务,只是因为您没有模板可以帮助您入门。
要创建服务,您只需创建一个普通的控制台应用程序即可。创建将负责实际服务实现的服务类。它看起来像这样
using System.ServiceProcess;
namespace WindowsService1
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
}
protected override void OnStop()
{
}
}
}
然后,服务启动代码可以进入您服务的Main
功能。
using System.ServiceProcess;
namespace WindowsService1
{
static class Program
{
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
}
}
}
这应该为您提供服务的基本框架。您需要的另一件事是为服务添加安装程序,以便可以将其安装为服务。以下内容应该让您入门,注意我已经对此进行了测试。
using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
namespace WindowsService1
{
[RunInstaller(true)]
public class ProjectInstaller : Installer
{
private ServiceProcessInstaller serviceProcessInstaller1;
private ServiceInstaller serviceInstaller1;
public ProjectInstaller()
{
this.serviceProcessInstaller1 = new ServiceProcessInstaller();
this.serviceInstaller1 = new ServiceInstaller();
this.serviceProcessInstaller1.Password = null;
this.serviceProcessInstaller1.Username = null;
this.serviceInstaller1.ServiceName = "Service1";
this.Installers.AddRange(new System.Configuration.Install.Installer[] {
this.serviceProcessInstaller1,
this.serviceInstaller1});
}
}
}
鉴于上述情况,您应该有足够的搜索周围或询问有关服务创建的更多详细信息。至于MSMQ监听器,您可以使用以下MSDN文章作为起点