首页 > 解决方案 > 如何在项目中创建ipc通信win-form

问题描述

 public partial class Form1 : Form
 {
   private Process subProcess;
   Counter counter = new Counter();
   public Form1(string[] args)
    {
        InitializeComponent();

        if (args.Length == 0 || args[0].IndexOf("-subMonitor") == -1)
        {
            IpcServerChannel serverChannel = new IpcServerChannel("serverchannel");

            RemotingConfiguration.RegisterWellKnownServiceType(typeof(Counter), "counter", WellKnownObjectMode.Singleton);
            Console.WriteLine("This is call number " + counter.Count); 
            Console.WriteLine("This is call number " + counter.Count);
            Console.WriteLine("Listening on " + serverChannel.GetChannelUri());

            // MainProcess
            subProcess = new Process();

            subProcess.StartInfo.FileName = Assembly.GetExecutingAssembly().Location;
            subProcess.StartInfo.Arguments = "-subMonitor";
            subProcess.StartInfo.UseShellExecute = false;

            subProcess.Start();

            Button btn = new Button();
            btn.Size = new Size(100, 100);
            btn.Location = new Point(0, 0);
            this.Controls.Add(btn);
            btn.BringToFront();

            btn.MouseUp += new System.Windows.Forms.MouseEventHandler(btnMouseUp);
        }
        else
        {

            Button btn = new Button();
            btn.Size = new Size(100, 100);
            btn.Location = new Point(0, 0);
            this.Controls.Add(btn);
            btn.BringToFront();

            btn.MouseUp += new System.Windows.Forms.MouseEventHandler(btnMouseUp);
            // SubProcess
            //Console.WriteLine(args[0]);

            IpcClientChannel clientChannel = new IpcClientChannel();
            RemotingConfiguration.RegisterWellKnownClientType(typeof(Counter), "ipc://serverchannel/counter");

        }

    }

    private void btnMouseUp(object sender, MouseEventArgs e)
    {
        MessageBox.Show(counter.Count.ToString());
    }
}



public class Counter : MarshalByRefObject
{

    private static int count = 0;
    public int Count
    {
        get
        {
            return (count++);
        }
    }
}

我想通过 ipc 与同一个程序进行通信。执行进程时打开相同的子进程。

为了测试,我制作了一个有价值的计数器,即单例对象。我想共享一个名为 Count 的单例对象。但它不工作。

我要一个结果......

如果我点击一个主 btn 按钮,这个结果是 2,3,4,5 如果我点击一个子 btn 按钮,这个结果是 6,7,8

但是这个结果是……

如果我点击一个主 btn 按钮,这个结果是 2,3,4,5 如果我点击一个子 btn 按钮,这个结果是 0,1,2...

它不是单例对象。

它有什么问题?

标签: c#winformsipc

解决方案


推荐阅读