gpt4 book ai didi

c# - 两个 .Net 应用程序之间的高效通信

转载 作者:可可西里 更新时间:2023-11-01 07:46:45 26 4
gpt4 key购买 nike

我目前正在用 C# 编写一个 .Net 应用程序,它有两个主要组件:

  1. DataGenerator - 一个生成大量数据的组件
  2. 查看器 - 能够可视化生成器创建的数据的 WPF 应用程序

这两个组件目前在我的解决方案中是两个独立的项目。此外,我正在使用 PRISM 4.0 框架来从这些组件中创建模块。

本质上,DataGenerator 生成大量数据并使用 PRISM 的 EventAggregator 发送事件,Viewer 订阅这些事件并为用户显示准备好的数据。

现在我的要求略有改变,这两个组件现在将在它们自己的应用程序中运行(但在同一台计算机上)。我仍然希望所有通信都是事件驱动的,我也仍然希望使用 PRISM 框架。

我的第一个想法是使用 WCF 来实现这两个应用程序之间的通信。然而,有一件事让生活变得更加艰难:

  1. DataGenerator 绝对不了解查看器(并且没有依赖关系)
  2. 如果我们没有打开查看器,或者关闭查看器应用程序,DataGenerator 应该仍然可以正常工作。
  3. 目前有很多事件从 DataGenerator(使用 EventAggregator)中产生:WCF 是否足够高效以在很短的时间内处理大量事件?

基本上,所有这些事件携带的数据都是非常简单的字符串、整数和 bool 值。如果没有 WCF,是否可以使用更轻量级的方法来执行此操作?

最后,如果 DataGenerator 可以发送这些事件并且可能有多个应用程序订阅它们(或没有),那就太好了。

非常感谢任何建议和提示。

谢谢!基督徒

编辑 1

我现在正在使用 WCF 和回调(如建议的那样)创建两个简单的控制台应用程序(一个托管服务并发送消息,另一个接收消息)。一旦我开始工作,我将添加工作代码。

编辑 2

好的 - 成功运行了一个简单的程序! :) 谢谢你们的帮助,伙计们!这是代码和图片,其中包含哪些类:

enter image description here

让我们从发件人开始:

在我的应用程序中,发送者包含服务接口(interface)及其实现。

IMessageCallback 为回调接口(interface):

namespace WCFSender
{
interface IMessageCallback
{
[OperationContract(IsOneWay = true)]
void OnMessageAdded(string message, DateTime timestamp);
}
}

ISimpleService 是服务契约:

namespace WCFSender
{
[ServiceContract(CallbackContract = typeof(IMessageCallback))]
public interface ISimpleService
{
[OperationContract]
void SendMessage(string message);

[OperationContract]
bool Subscribe();

[OperationContract]
bool Unsubscribe();
}
}

SimpleService 是 ISimpleService 的实现:

public class SimpleService : ISimpleService
{
private static readonly List<IMessageCallback> subscribers = new List<IMessageCallback>();

public void SendMessage(string message)
{
subscribers.ForEach(delegate(IMessageCallback callback)
{
if (((ICommunicationObject)callback).State == CommunicationState.Opened)
{
callback.OnMessageAdded(message, DateTime.Now);
}
else
{
subscribers.Remove(callback);
}
});
}

public bool Subscribe()
{
try
{
IMessageCallback callback = OperationContext.Current.GetCallbackChannel<IMessageCallback>();
if (!subscribers.Contains(callback))
subscribers.Add(callback);
return true;
}
catch
{
return false;
}
}

public bool Unsubscribe()
{
try
{
IMessageCallback callback = OperationContext.Current.GetCallbackChannel<IMessageCallback>();
if (!subscribers.Contains(callback))
subscribers.Remove(callback);
return true;
}
catch
{
return false;
}
}
}

在 Program.cs(在发件人端)中,托管服务并发送消息:

[CallbackBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)]
class Program : SimpleServiceReference.ISimpleServiceCallback, IDisposable
{
private SimpleServiceClient client;

static void Main(string[] args)
{
ServiceHost myService = new ServiceHost(typeof(SimpleService));
myService.Open();
Program p = new Program();
p.start();

Console.ReadLine();
}

public void start()
{
InstanceContext context = new InstanceContext(this);

client = new SimpleServiceReference.SimpleServiceClient(context, "WSDualHttpBinding_ISimpleService");

for (int i = 0; i < 100; i++)
{
client.SendMessage("message " + i);
Console.WriteLine("sending message" + i);
Thread.Sleep(600);
}
}

public void OnMessageAdded(string message, DateTime timestamp)
{
throw new NotImplementedException();
}

public void Dispose()
{
client.Close();
}
}

此外,请注意服务引用已添加到 Sender 项目中!

现在让我们进入接收端:

正如在发件人中所做的那样,我将服务引用添加到项目中。

只有一个类,Program.cs:

[CallbackBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)]
class Program : SimpleServiceReference.ISimpleServiceCallback, IDisposable
{
private SimpleServiceClient client;

static void Main(string[] args)
{
Program p = new Program();
p.start();
Console.ReadLine();
p.Dispose();
}

public void start()
{
InstanceContext context = new InstanceContext(this);

client = new SimpleServiceReference.SimpleServiceClient(context, "WSDualHttpBinding_ISimpleService");
client.Subscribe();
}

public void OnMessageAdded(string message, DateTime timestamp)
{
Console.WriteLine(message + " " + timestamp.ToString());
}

public void Dispose()
{
client.Unsubscribe();
client.Close();
}
}

最后剩下的是 app.config 文件。在客户端,app.config 是通过添加服务引用自动生成的。在服务器端,我稍微更改了配置,但其中的一部分也是通过添加服务引用自动生成的。请注意,您需要在添加服务引用之前进行更改:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<bindings>
<wsDualHttpBinding>
<binding name="WSDualHttpBinding_ISimpleService" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<reliableSession ordered="true" inactivityTimeout="00:10:00" />
<security mode="Message">
<message clientCredentialType="Windows" negotiateServiceCredential="true"
algorithmSuite="Default" />
</security>
</binding>
</wsDualHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:8732/Design_Time_Addresses/WCFSender/SimpleService/"
binding="wsDualHttpBinding" bindingConfiguration="WSDualHttpBinding_ISimpleService"
contract="SimpleServiceReference.ISimpleService" name="WSDualHttpBinding_ISimpleService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
</client>
<behaviors>
<serviceBehaviors>
<behavior name="MessageBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="WCFSender.SimpleService" behaviorConfiguration="MessageBehavior">
<endpoint address="" binding="wsDualHttpBinding" contract="WCFSender.ISimpleService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8732/Design_Time_Addresses/WCFSender/SimpleService/" />
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
</configuration>

重要提示:我设法使用教程实现了这两个非常简单的应用程序。上面的代码对我有用,希望能帮助其他人理解 WCF 回调。它不是编写得非常好的代码,不应该完全使用!这只是一个简单的示例应用。

最佳答案

不要担心性能,如果配置得当,wcf 可以达到非常高的吞吐量。为您的事件使用回调:http://www.switchonthecode.com/tutorials/wcf-tutorial-events-and-callbacks

关于c# - 两个 .Net 应用程序之间的高效通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7651915/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com