我正在使用C#编写一个.Net应用程序,它有两个主要组件:
- DataGenerator - 生成大量数据的组件
- Viewer - 能够可视化生成器创建的数据的WPF应用程序
这两个组件目前是解决方案中的两个单独的项目。此外,我正在使用PRISM 4.0框架将这些组件制作成模块。
实际上,DataGenerator会生成大量数据,并使用PRISM的EventAggregator发送事件,而Viewer则订阅这些事件并显示准备好供用户使用的数据。
现在我的需求略有改变,这两个组件将在自己的应用程序中运行(但在同一台计算机上)。我仍然希望所有通信都是事件驱动的,而且我还想继续使用PRISM框架。
我的第一个想法是使用WCF在这两个应用程序之间进行通信。然而,有一件事情使得生活有些困难:
- DataGenerator完全不知道Viewer(也没有依赖关系)
- 如果我们不打开viewer或关闭viewer应用程序,则DataGenerator应该仍然正常工作。
- 目前有很多事件从DataGenerator中产生(使用EventAggregator):WCF是否足够高效地处理大量事件?
基本上,所有这些事件携带的数据都是非常简单的字符串、整数和布尔值。是否有更轻量级的方法来实现这一点,而不使用WCF?
最后,如果DataGenerator可以发送这些事件,并且可能有一个以上的应用程序订阅它们(或没有订阅),那将很好。
非常感谢任何建议和提示。
谢谢!
Christian
编辑1
我现在正在创建两个简单的控制台应用程序(一个托管服务和发送消息,另一个接收消息),使用WCF和回调(如建议所述)。一旦我使其正常工作,我将添加可运行代码。
编辑2
好的- 成功运行简单的程序! :) 感谢您的帮助!以下是代码和显示类的图片:
让我们从发送者开始:
在我的应用程序中,发送者包含服务接口及其实现。
IMessageCallback是回调接口:
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();
}
}
此外,请注意已将服务引用添加到发送方项目中!
现在让我们来到接收方:
如同在发送方中所做的那样,我已经将服务引用添加到这个项目中。
只有一个类,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 回调。这不是非常优秀的代码,不应该完全使用!它仅仅是一个简单的示例应用程序。