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

17

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

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

这两个组件目前是解决方案中的两个单独的项目。此外,我正在使用PRISM 4.0框架将这些组件制作成模块。

实际上,DataGenerator会生成大量数据,并使用PRISM的EventAggregator发送事件,而Viewer则订阅这些事件并显示准备好供用户使用的数据。

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

我的第一个想法是使用WCF在这两个应用程序之间进行通信。然而,有一件事情使得生活有些困难:

  1. DataGenerator完全不知道Viewer(也没有依赖关系)
  2. 如果我们不打开viewer或关闭viewer应用程序,则DataGenerator应该仍然正常工作。
  3. 目前有很多事件从DataGenerator中产生(使用EventAggregator):WCF是否足够高效地处理大量事件?

基本上,所有这些事件携带的数据都是非常简单的字符串、整数和布尔值。是否有更轻量级的方法来实现这一点,而不使用WCF?

最后,如果DataGenerator可以发送这些事件,并且可能有一个以上的应用程序订阅它们(或没有订阅),那将很好。

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

谢谢!
Christian

编辑1

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

编辑2

好的- 成功运行简单的程序! :) 感谢您的帮助!以下是代码和显示类的图片:

enter image description here

让我们从发送者开始:

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

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 回调。这不是非常优秀的代码,不应该完全使用!它仅仅是一个简单的示例应用程序。

3个回答

7

那么你认为 WCF 能够处理有未知数量应用程序监听事件的情况吗? - Christian
@Christian:使用Microsoft StreamInsight 1.2。 - Alan Turing
@Artur Mustafin - 哇,刚刚了解了StreamInsight是什么。这似乎是更有效的方法。然而,我认为在我的情况下简单的WCF回调就足够了。 - Christian

4

1

使用Microsoft StreamInsight 1.2。使用案例描述,它可以嵌入应用程序、WCF服务或两者兼而有之。

阅读MSDN文章关于StreamInsight 1.2:

Microsoft® StreamInsight 是微软的复杂事件处理技术,帮助企业创建事件驱动应用程序,并通过将来自多个来源的事件流进行相关性分析,实现更好的洞察力和近乎零延迟的效果。
Microsoft StreamInsight™ 是一个强大的平台,可用于开发和部署复杂事件处理(CEP)应用程序。其高吞吐量的流处理架构和基于 Microsoft .NET Framework 的开发平台使您能够快速实现强大且高效的事件处理应用程序。事件流源通常包括来自制造应用程序、金融交易应用程序、Web 分析和运营分析的数据。通过使用 StreamInsight,您可以开发 CEP 应用程序,通过降低提取、分析和相关数据的成本,从这些原始数据中获得即时的商业价值,并允许您几乎立即监视、管理和挖掘数据以获取条件、机会和缺陷。
通过使用 StreamInsight 开发 CEP 应用程序,您可以为您的业务实现以下战术和战略目标:
- 监视来自多个来源的数据,寻找有意义的模式、趋势、异常和机会。 - 在数据处于飞行状态时增量分析和相关数据,而无需先存储数据,从而产生非常低的延迟。从多个来源聚合看似不相关的事件,并随时间执行高度复杂的分析。 - 通过对事件进行低延迟分析并触发响应操作,来管理您的业务关键绩效指标(KPI)。 - 将 KPI 定义纳入 CEP 应用程序的逻辑中,以快速响应机会或威胁,从而提高运营效率和快速响应业务机会的能力。 - 挖掘事件以获取新的业务 KPI。 - 通过挖掘历史数据不断完善和改进您的 KPI 定义,向预测性业务模型迈进。

更多信息和示例可以在CodePlex上找到:


谢谢你的提示。我一定会查看CodePlex的示例,看看将其引入我的应用程序是否会带来很多开销。此外,我还需要考虑框架是否足够轻量级,因为它应该尽可能轻量级。 - Christian
最好用一份经过深思熟虑的优缺点列表来替换那些充斥着营销术语的剪贴板文本。至少,把这样的文本括在引号中(我已经这样做了),因为我怀疑你自己写的。 :) - Macke

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接