在C#中两个进程之间进行通信的最简单方法是什么?
在同一台机器上有两个独立的项目A和B(你有他们的源代码),两者都可以编译成EXE文件。 当A运行时,有一个类的实例,比方说a
,我们希望它在运行时在B中的数据。 什么是最简单的方法? 一个面试问题和我的回答是:序列化它并在B中反序列化。但是面试官对这个答案并不满意,因为他告诉我“它可以更容易”。 最后我放弃了,因为我没有更好的解决方案。 你的想法是什么?
内存映射文件可能吗?
我认为使用NamedPipes (System.IO.Pipes)
NamedPipeServerStream在这种情况下会更好用。
有点晚了但你可以做到这一点……
不容易
服务器代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Server { class Program { static void Main(string[] args) { var i = 0; while(true) { Console.WriteLine(Console.ReadLine() + " -> " + i++); } } } }
客户代码
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; namespace Client { class Program { static void Main(string[] args) { Process p = new Process(); p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardInput = true; p.StartInfo.FileName = "Server.exe"; p.Start(); var t = new Thread(() => { while (true) { Console.WriteLine(p.StandardOutput.ReadLine()); }}); t.Start(); while (true) { p.StandardInput.WriteLine(Console.ReadLine()); } } } }