簡體   English   中英

2個C#進程之間最簡單的進程間通信方法是什么?

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

我想在父進程和子進程之間創建通信,兩者都用 C# 編寫。

它應該是異步的、事件驅動的。

我不想在每個進程中運行一個線程來處理非常罕見的通信。

什么是最好的解決方案?

匿名管道

將異步操作與 BeginRead/BeginWrite 和 AsyncCallback 一起使用。

如果您的進程在同一台計算機上,您可以簡單地使用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();
}

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

我建議使用 Windows Communication Foundation:

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

您可以來回傳遞對象,使用各種不同的協議。 我建議使用二進制 tcp 協議。

還有COM

有一些技術細節,但我想說的優點是您將能夠調用您可以定義的方法。

MSDN 提供 C# COM 互操作教程。 請搜索,因為這些鏈接確實會發生變化。

要立即開始,請訪問這里...

還有 MSMQ(Microsoft 消息隊列),它可以跨網絡運行,也可以在本地計算機上運行。 盡管有更好的交流方式,但值得研究:https ://msdn.microsoft.com/en-us/library/ms711472(v=vs.85).aspx

當安全性不是問題並且考慮到您的約束(同一台機器上的兩個 C# 進程)時,用於進程間通信的 C# 中最簡單的解決方案是 Remoting API。 現在 Remoting 是一項遺留技術(與已棄用的技術不同),不鼓勵在新項目中使用,但它確實運行良好,並且不需要太多的排場和環境即可開始工作。

MSDN 上有一篇出色的文章,介紹了使用Remoting 框架中的IpcChannel類( IpcChannel Greg Beech 在這里找到)來設置簡單的遠程處理服務器和客戶端。

我建議先嘗試這種方法,然后嘗試將您的代碼移植到 WCF(Windows 通信框架)。 這有幾個優點(更好的安全性、跨平台),但必然更復雜。 幸運的是,MSDN 有一篇非常好的文章將代碼從 Remoting 移植到 WCF

如果您想立即深入了解WCF,這里有一個很棒的教程

死靈法

如果可能的話,制作共享文件會更容易!

//out
File.AppendAllText("sharedFile.txt", "payload text here");
// in
File.ReadAllText("sharedFile.txt");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM