C#WinForms:两种应用程序可以通过多种方式进行对话,但我并不是很了解这方面的知识,但是MSMQ和命名管道这些东西出现在我脑海中,但不知道什么是最好的。所以这里是场景,你认为最好的办法是:哪个通信技术更适合在两个应用程序之间进行通信
比方说,我写了一个Windows服务,有时候备份一些文件到某个地方。 用户打开一些我的应用程序XYX,我希望他得到通知,嘿在那里有新的备份文件。
就是这样。这是这种情况。
C#WinForms:两种应用程序可以通过多种方式进行对话,但我并不是很了解这方面的知识,但是MSMQ和命名管道这些东西出现在我脑海中,但不知道什么是最好的。所以这里是场景,你认为最好的办法是:哪个通信技术更适合在两个应用程序之间进行通信
比方说,我写了一个Windows服务,有时候备份一些文件到某个地方。 用户打开一些我的应用程序XYX,我希望他得到通知,嘿在那里有新的备份文件。
就是这样。这是这种情况。
使用MSMQ,因为它很容易实现,你可以玩对象。生产者和消费者可以非常简单地彼此交互。这两个应用程序(生产者,COnsumer)可以位于同一台计算机上,通过网络,甚至不在总是连接的不同计算机上。 MSMQ被认为是故障安全的,因为如果第一次传输失败,它将重试发送消息。这使您可以非常确信您的应用程序消息将到达目的地。
我们只是使用命名管道在最近的一个项目类似的目的。代码结果非常简单。我不能居功这个特殊的代码,但在这里它是:
/// <summary>
/// This will attempt to open a service to listen for message requests.
/// If the service is already in use it means that another instance of this WPF application is running.
/// </summary>
/// <returns>false if the service is already in use by another WPF instance and cannot be opened; true if the service sucessfully opened</returns>
private bool TryOpeningTheMessageListener()
{
try
{
NetNamedPipeBinding b = new NetNamedPipeBinding();
sh = new ServiceHost(this);
sh.AddServiceEndpoint(typeof(IOpenForm), b, SERVICE_URI);
sh.Open();
return true;
}
catch (AddressAlreadyInUseException)
{
return false;
}
}
private void SendExistingInstanceOpenMessage(int formInstanceId, int formTemplateId, bool isReadOnly, DateTime generatedDate, string hash)
{
try
{
NetNamedPipeBinding b = new NetNamedPipeBinding();
var channel = ChannelFactory<IOpenForm>.CreateChannel(b, new EndpointAddress(SERVICE_URI));
channel.OpenForm(formInstanceId, formTemplateId, isReadOnly, generatedDate, hash);
(channel as IChannel).Close();
}
catch
{
MessageBox.Show("For some strange reason we couldnt talk to the open instance of the application");
}
}
在我们OnStartup我们刚刚
if (TryOpeningTheMessageListener())
{
OpenForm(formInstanceId, formTemplate, isReadOnly, generatedDate, hash);
}
else
{
SendExistingInstanceOpenMessage(formInstanceId, formTemplate, isReadOnly, generatedDate, hash);
Shutdown();
return;
}
感谢关于使用Pipes的很好的例子。 – Bohn
有很多方法可以实现你问什么;
为您的情况,您可以用数据库:)你可以添加记录,当你把备份数据库做到这一点,当XYX应用中打开,你可以检查从数据库的备份,并通知 – Damith
是的,这是true..even更简单,在文本文件中写入新行:)但其他优雅的方式呢?让老板印象深刻的东西!就像他说的哦,他已经使用XYZ来做到这一点! – Bohn
数据库将是额外的开销。你需要安装一些数据库到每个客户端机器上,这个应用程序将被托管。而MSMQ和命名管道是Windows的本地组件。随着文本文件(因此命名管道),你将不得不担心的唯一的事情就是你会玩流而不是对象! – Anand