c#進程間通訊方案之IPC通道


轉載:http://www.cnphp.info/csharp-ipc-channel-remoting.html

最近一直糾結與使用多進程還是多線程來構建程序。多線程的方法似乎不錯,但是一個進程可承受的線程數有有限的,並且由於每個線程都與UI有着些許關系,線程的工作大多數時間浪費在阻塞上了,效率實在不是很高。

筆者遂在google上搜索進程間通訊的方案。發現有很多種,其中IPC通道似乎是個不錯的選擇,支持本機的進程間通訊,可以作為備選方案之一,下面介紹以下基本的編程方法,以作備忘。

首先建立一個IPC通訊中使用的對象,其中MarshalByRefObject 是必須的

 

   1:  using System;
   2:   
   3:  namespace Ipctest
   4:  {
   5:      public class test:MarshalByRefObject
   6:      {
   7:          private int iCount = 0;
   8:          public int count()
   9:          {
  10:              iCount++;
  11:              return iCount;
  12:          }
  13:   
  14:          public int Add(int x)
  15:          {
  16:              iCount += x;
  17:              return iCount;
  18:          }
  19:      }
  20:  }

接着建一個服務端控制台程序

   1:  using System;
   2:  using System.Runtime.Remoting;
   3:  using System.Runtime.Remoting.Channels;
   4:  using System.Runtime.Remoting.Channels.Ipc;
   5:   
   6:  namespace Ipctest
   7:  {
   8:      class Program
   9:      {
  10:          static void Main(string[] args)
  11:          {
  12:             IpcChannel serverchannel = new IpcChannel("testchannel");
  13:              ChannelServices.RegisterChannel(serverchannel,false);
  14:              RemotingConfiguration.RegisterWellKnownServiceType(typeof(test), "test", WellKnownObjectMode.Singleton);
  15:              Console.WriteLine("press Enter to exit");
  16:              Console.ReadLine();
  17:              Console.WriteLine("server stopped");
  18:          }
  19:      }
  20:  }

最后是客戶端控制台程序

   1:  using System;
   2:  using System.Runtime.Remoting;
   3:  using System.Runtime.Remoting.Channels;
   4:  using System.Runtime.Remoting.Channels.Ipc;
   5:   
   6:  namespace Ipctest
   7:  {
   8:      class Program
   9:      {
  10:          static void Main(string[] args)
  11:          {
  12:              IpcChannel tcc = new IpcChannel();
  13:              ChannelServices.RegisterChannel(tcc,false);
  14:              WellKnownClientTypeEntry remotEntry = new WellKnownClientTypeEntry(typeof(test), "ipc://testchannel/test");
  15:              RemotingConfiguration.RegisterWellKnownClientType(remotEntry);
  16:   
  17:              test st = new test();
  18:              Console.WriteLine("{0},{1}",st.count(),st.Add(1));
  19:              Console.ReadLine();
  20:          }
  21:      }
  22:  }

在測試的過程中會發現第一次調用客戶端輸出結果:

1,2

第二次輸出結果

3,4

……

結果是比較符合要求的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM