What's the easiest way to communicate between two processes in C#?

拈花ヽ惹草 提交于 2019-12-21 23:47:19

问题


There are two independent projects A and B(you have their source code) on the same machine, both can be compiled to EXE file. When A is running there is an instance of some class, let's say a, we want its data in B when running. What's the easiest way? An interview question and my answer is: serialize it and de-serialize in B. But the interviewer is not satisfied with this answer because he told me "it can be easier". At last I gave up because I don't have any better solution. What's your ideas?


回答1:


Memory mapped files maybe?




回答2:


I think using NamedPipes (System.IO.Pipes) NamedPipeServerStream would work better in this case.




回答3:


A little bit late but you can do this ...

cannot be easier

Server code

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++);
            }
        }
    }
}

Client Code

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());
            }
        }
    }
}


来源:https://stackoverflow.com/questions/5163077/whats-the-easiest-way-to-communicate-between-two-processes-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!