WPF利用RPC调用其他进程的方法详解

2019-12-30 19:44:56王冬梅

前言

如果在 WPF 需要用多进程通信,一个推荐的方法是 WCF ,因为 WCF 是 RPC 计算。先来讲下 RPC (Remote Procedure Call) 远程过程调用,他是通过特定协议,包括 tcp 、http 等对其他进程进行调用的技术。详细请看百度

现在不会告诉大家如何使用 WCF ,下面讲的是使用 remoting 这个方法。需要知道 dotnet remoting 是已经过时的技术,建议使用 wcf 但是 wcf 部署难度比较高,对于性能要求比较高或想快速使用,建议使用 remoting 。使用方法很简单

首先创建三个工程,一个工程放其他两个需要使用的库,一个是服务端,一个是客户端。其中客户端就可以调用服务端,客户端和服务端是两个不同的进程,所以可以跨进程调用。

方法如下:

先创建一个简单的工程,库的工程 RemoteObject ,里面只有一个类


 public class RemoteCalculator : MarshalByRefObject
 {
  public const int Port = 13570;

  public int Add(int a, int b)
  {
   return a + b;
  }
 }

注意这个类需要继承 MarshalByRefObject ,这个类是在两个进程引用,客户端不实现这个类,所以客户端使用这个类接口同样可以。具体调用这个类的方法在服务端运行,结果通过 tcp 或 http 返回。

客户端的主要代码是连接服务端,然后访问库的 add 函数,但是这个函数不在客户端运行,通过 tcp 调用服务端,让他运行。


  private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
  {
   if (_channel == null)
   {
    Process.Start("CalcnsMnlhzydYeuiitcCddhxvlhm.exe");
    _channel = new TcpChannel();
    ChannelServices.RegisterChannel(_channel, true);
   }
   var calculator = (RemoteCalculator) Activator.GetObject(typeof(RemoteCalculator),
    "tcp://" + "127.0.0.1" + ":" + RemoteCalculator.Port + "/RemoteCalculator");
   Console.WriteLine(calculator.Add(1, 2));
  }

服务端的名称是 CalcnsMnlhzydYeuiitcCddhxvlhm ,主要是打开连接,执行客户端发过来的函数


  static void Main(string[] args)
  {
   new Thread(() =>
   {
    _channel = new TcpChannel(RemoteCalculator.Port);

    ChannelServices.RegisterChannel(_channel, true);
    RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemoteCalculator), "RemoteCalculator", WellKnownObjectMode.Singleton);
   }).Start();
   while (true)
   {
    Console.ReadKey();
   }
  }
  private static TcpChannel _channel;

需要注意,客户端点击按钮需要先打开服务端,使用这个代码Process.Start("CalcnsMnlhzydYeuiitcCddhxvlhm.exe");然后创建 tcp 告诉通过tcp和服务端连接。然后从服务端获得 calculator 这个类,实际这个类现在是没有实现,调用函数需要发送到服务端。

服务端需要打开 TcpChannel ,这时需要定义调用的类,