程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> 關於C# >> c#進程間通訊方案之IPC通道

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

編輯:關於C#
 

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

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

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

using System;

namespace Ipctest
{
public class test:MarshalByRefObject
{
private int iCount = 0;
public int count()
{
iCount++;
return iCount;
}

public int Add(int x)
{
iCount += x;
return iCount;
}
}
}

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

using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;

namespace Ipctest
{
class Program
{
static void Main(string[] args)
{
IpcChannel serverchannel = new IpcChannel("testchannel");
ChannelServices.RegisterChannel(serverchannel,false);
RemotingConfiguration.RegisterWellKnownServiceType(typeof(test), "test", WellKnownObjectMode.Singleton);
Console.WriteLine("press Enter to exit");
Console.ReadLine();
Console.WriteLine("server stopped");
}
}
}
最後是客戶端控制台程序

using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;

namespace Ipctest
{
class Program
{
static void Main(string[] args)
{
IpcChannel tcc = new IpcChannel();
ChannelServices.RegisterChannel(tcc,false);
WellKnownClientTypeEntry remotEntry = new WellKnownClientTypeEntry(typeof(test), "ipc://testchannel/test");
RemotingConfiguration.RegisterWellKnownClientType(remotEntry);

test st = new test();
Console.WriteLine("{0},{1}",st.count(),st.Add(1));
Console.ReadLine();
}
}
}
在測試的過程中會發現第一次調用客戶端輸出結果:

1,2

第二次輸出結果

3,4

……

結果是比較符合要求的。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved