2 C#进程之间最简单的进程间通信方法是什么?

Hor*_*ux7 57 c# ipc

我想要用C#编写的父进程和子进程之间的通信.它应该是异步的,事件驱动的.我不希望在处理非常罕见的通信的每个进程中运行一个线程.

什么是最好的解决方案?

Car*_*rra 39

匿名管道.

http://msdn.microsoft.com/en-us/library/bb546102.aspx

使用与BeginRead/BeginWrite和AsyncCallback的异步操作.


小智 16

如果你的进程在同一台计算机上,你可以简单地使用stdio.

这是我的用法,一个网页截图:

var jobProcess = new Process();

jobProcess.StartInfo.FileName = Assembly.GetExecutingAssembly().Location;
jobProcess.StartInfo.Arguments = "job";

jobProcess.StartInfo.CreateNoWindow = false;
jobProcess.StartInfo.UseShellExecute = false;

jobProcess.StartInfo.RedirectStandardInput = true;
jobProcess.StartInfo.RedirectStandardOutput = true;
jobProcess.StartInfo.RedirectStandardError = true;

// Just Console.WriteLine it.
jobProcess.ErrorDataReceived += jp_ErrorDataReceived;

jobProcess.Start();

jobProcess.BeginErrorReadLine();

try
{
    jobProcess.StandardInput.WriteLine(url);
    var buf = new byte[int.Parse(jobProcess.StandardOutput.ReadLine())];
    jobProcess.StandardOutput.BaseStream.Read(buf, 0, buf.Length);
    return Deserz<Bitmap>(buf);
}
finally
{
    if (jobProcess.HasExited == false)
        jobProcess.Kill();
}
Run Code Online (Sandbox Code Playgroud)

检测Main上的args

static void Main(string[] args)
{
    if (args.Length == 1 && args[0]=="job")
    {
        //because stdout has been used by send back, our logs should put to stderr
        Log.SetLogOutput(Console.Error); 

        try
        {
            var url = Console.ReadLine();
            var bmp = new WebPageShooterCr().Shoot(url);
            var buf = Serz(bmp);
            Console.WriteLine(buf.Length);
            System.Threading.Thread.Sleep(100);
            using (var o = Console.OpenStandardOutput())
                o.Write(buf, 0, buf.Length);
        }
        catch (Exception ex)
        {
            Log.E("Err:" + ex.Message);
        }
    }
    //...
}
Run Code Online (Sandbox Code Playgroud)

  • 但是,如果目标进程需要一个GUI,即`ProcessStartInfo.UseShellExecute`是'true`,则无法工作.在这种情况下,您无法重定向标准输出和错误. (4认同)

bob*_*olt 8

我建议使用Windows Communication Foundation:

http://en.wikipedia.org/wiki/Windows_Communication_Foundation

您可以来回传递对象,使用各种不同的协议.我建议使用二进制tcp协议.

  • 那么复杂的方式是什么呢? (73认同)
  • 如果WCF是"最简单的方法",我真的想哭:P (65认同)
  • @ kizzx2我们开始以相当大的方式进入WCF,一旦您经历了最初的困惑,WCF真的很棒。我发现这个人的简单实现非常有用http://www.devx.com/codemag/Article/39837 (2认同)
  • @CharlieAspinall,如果5页C#和XML很简单。我真的很想哭。 (2认同)