What is the simplest method of inter-process communication between 2 C# processes?

后端 未结 7 1686
甜味超标
甜味超标 2020-11-22 07:31

I want to create a communication between a parent and a child process, both written in C#.

It should be asynchronous, event-driven.

I don\'t want to run a thre

7条回答
  •  长情又很酷
    2020-11-22 08:25

    If your processes in same computer, you can simply use stdio.

    This is my usage, a web page screenshooter:

    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(buf);
    }
    finally
    {
        if (jobProcess.HasExited == false)
            jobProcess.Kill();
    }
    

    Detect args on Main

    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);
            }
        }
        //...
    }
    

提交回复
热议问题