C#WinForms:有几种方法可以让两个应用程序一起对话,我在这方面不是很了解,但我想到了像MSMQ和命名管道这样的东西,但不确定哪种是最好的。下面是一个场景,您认为最好的方法是什么:
比方说,我编写了一个windows服务,有时会将一些文件备份到某个地方。用户打开一些我的应用程序XYX,我希望他被通知,嘿,有新的备份文件为您在那里。
就这样。这就是这个场景。
发布于 2012-06-18 12:51:20
使用MSMQ是因为它的实现非常简单,而且你可以使用对象。生产者和消费者可以彼此交互,两个应用程序( Producer,COnsumer)可以在同一台机器上,跨越网络,甚至在不总是连接的不同机器上。MSMQ被认为是故障安全的,因为如果第一次传输失败,它将重试发送消息。这使您非常有信心,您的应用程序消息将到达它们的目的地。
More Details
发布于 2012-06-18 12:54:32
在最近的一个项目中,我们刚刚将命名管道用于类似的目的。代码变得非常简单。我不能为这段特定的代码声称自己的功劳,但它是这样的:
/// <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;
}发布于 2012-06-18 12:59:33
有很多方法可以实现你所要求的;
正如达米斯所说,
https://stackoverflow.com/questions/11076973
复制相似问题