简体   繁体   中英

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

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?

内存映射文件可能吗?

我认为在这种情况下使用NamedPipes (System.IO.Pipes) NamedPipeServerStream会更好。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM