最近在調試一個算法,想通過改變算法的參數看看結果有什麼變化。 碰到一個麻煩的事情是,從磁盤加載、構建數據需要15分鐘。這就比較討厭了,也就是說我每次調一個參數前都要等15分鐘啟動時間?
於是我就想,能不能開一個datahost進程專門加載數據。我在別的進程調試參數,但需要用數據時就直接從datahost進程中加載現成的數據。 這樣的話我只需要從磁盤加載一次數據。 於是找了一下, c#有個叫IPC(inter process communication)的功能可以實現同一台機器上的不同進程間通信。
注意我這裡的scenario:我需要進程間通信“數據對象”, 而不是消息。 通信消息比較好辦,就傳一個string流就行了。而我需要傳遞的是數據對象,比如一個Dictionary, 或者自定義class。
IPC的大致過程是這樣的:datahost進程先綁定一個對象,client根據對象的uri去訪問對象類, 並且調用該類的方法。datahost進程接收到從client發來的調用,就會實例化一個對象(注意,在這個時候才開始實例化一個對象,這也是我的代碼裡使用static的原因),並且執行相關的函數,再把結果返回給client。 注意執行過程是在datahost端的。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IPCServer
{
public class DataObj : MarshalByRefObject
{
public static Dictionary<string, int> salary;
public static string company;
public static int counter;
public static int constructerCnt = 0;
public static void LoadData()
{
company = "Microsoft";
salary = new Dictionary<string, int>();
salary.Add("lianjx", 3);
salary.Add("uncle", 5);
counter = 0;
}
public Dictionary<string, int> GetSalary()
{
return DataObj.salary;
}
public DataObj()
{
DataObj.constructerCnt++;
Console.WriteLine("Constructer...{0}", DataObj.constructerCnt);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;
using System.Text;
using System.Threading.Tasks;
namespace IPCServer
{
class Program
{
static void Main(string[] args)
{
IpcServerChannel channel = new IpcServerChannel("ServerChannel");
ChannelServices.RegisterChannel(channel, false);
DataObj.LoadData();
DataObj.salary.Add("jian", 23);
DataObj.salary.Add("xun", 22);
RemotingConfiguration.RegisterWellKnownServiceType(typeof(DataObj), "DataObj", WellKnownObjectMode.SingleCall);
Console.WriteLine("press anykey to exit");
Console.ReadKey();
}
}
}
using IPCServer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;
using System.Text;
using System.Threading.Tasks;
namespace IPCClient
{
class Program
{
static void Main(string[] args)
{
IpcClientChannel channel = new IpcClientChannel();
ChannelServices.RegisterChannel(channel, false);
DataObj obj = null;
for (int t = 0; t < 1; t++)
{
Console.WriteLine("t={0}", t);
try
{
obj = (DataObj)Activator.GetObject(typeof(DataObj), "ipc://ServerChannel/DataObj");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
if (obj == null)
{
Console.WriteLine("could not locate server");
}
else
{
foreach (var pair in obj.GetSalary())
{
Console.WriteLine("{0},{1}", pair.Key, pair.Value);
}
Console.WriteLine("counter = {0}", obj.GetSalary());
DataObj.counter++;
}
}
Console.WriteLine("Mission Complete!");
Console.ReadKey();
}
}
}
事實上結果並沒有加速。估計IPC也是把對象序列化後傳遞,再反序列化的吧。 桑心。
next steps: 尋找一種直接讀其他進程的內存空間的途徑。。。
轉至:http://www.cnblogs.com/sylvanas2012/p/4294393.html