2012-06-18 43 views
2

C#WinForms:两种应用程序可以通过多种方式进行对话,但我并不是很了解这方面的知识,但是MSMQ和命名管道这些东西出现在我脑海中,但不知道什么是最好的。所以这里是场景,你认为最好的办法是:哪个通信技术更适合在两个应用程序之间进行通信

比方说,我写了一个Windows服务,有时候备份一些文件到某个地方。 用户打开一些我的应用程序XYX,我希望他得到通知,嘿在那里有新的备份文件。

就是这样。这是这种情况。

+0

为您的情况,您可以用数据库:)你可以添加记录,当你把备份数据库做到这一点,当XYX应用中打开,你可以检查从数据库的备份,并通知 – Damith

+0

是的,这是true..even更简单,在文本文件中写入新行:)但其他优雅的方式呢?让老板印象深刻的东西!就像他说的哦,他已经使用XYZ来做到这一点! – Bohn

+0

数据库将是额外的开销。你需要安装一些数据库到每个客户端机器上,这个应用程序将被托管。而MSMQ和命名管道是Windows的本地组件。随着文本文件(因此命名管道),你将不得不担心的唯一的事情就是你会玩流而不是对象! – Anand

回答

1

使用MSMQ,因为它很容易实现,你可以玩对象。生产者和消费者可以非常简单地彼此交互。这两个应用程序(生产者,COnsumer)可以位于同一台计算机上,通过网络,甚至不在总是连接的不同计算机上。 MSMQ被认为是故障安全的,因为如果第一次传输失败,它将重试发送消息。这使您可以非常确信您的应用程序消息将到达目的地。

More Details

+0

谢谢阿南德,我之前发布了一个MSMQ问题,想知道如果你有半分钟的时间你能帮我解决吗? HTTP://计算器。com/questions/11076790/the-bare-minimum-needed-to-write-a-msmq-sample-application – Bohn

+1

检查上面的链接,我已经在你的问题本身发布了我的答案 – Anand

1

我们只是使用命名管道在最近的一个项目类似的目的。代码结果非常简单。我不能居功这个特殊的代码,但在这里它是:

/// <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; 
     } 
+0

感谢关于使用Pipes的很好的例子。 – Bohn

0

有很多方法可以实现你问什么;

  1. 正如Damith所说的那样,进入数据库并从中读取数据。
  2. 在文件中输入内容并从中读取。
  3. 使用WCF - Windows Communication Foundation并将配置设置为使用MSMQ绑定。阅读WCF & MSMQ文章,让你开始。
相关问题