代码之家  ›  专栏  ›  技术社区  ›  Dor Cohen

在不同的过程中与类通信[重复]

  •  2
  • Dor Cohen  · 技术社区  · 12 年前

    我有一个名为 worker ,我想在一个新的进程中创建这个类的新实例。
    但我希望在这个类将在一个新的过程中打开并能够发送和接收数据后,能够与它进行通信。

    我想做的是,在任何电话中 worker() 一个新的实例将在一个新进程中打开,这样我就可以在我的任务管理器中看到很多worker.exe。

    我以前用vb-com包装器做过,但现在我只想在C#中做这件事,
    我能用最基本的方法吗?

    分类示例:

    public class worker
    {
        public worker()
        {
            // Some code that should be open in a new process
        }
    
        public bool DoAction()
        {
            return true;
        }
    }
    

    主程序示例:

    worker myWorker = new worker();//should be open in a new process
    bool ret = myWorker.DoAction();
    
    2 回复  |  直到 12 年前
        1
  •  3
  •   Dor Cohen    12 年前

    您可以在WCF终结点中公开您的操作。然后,从一个过程开始,开始另一个过程。然后,您可以连接到该进程公开的端点,以便与其进行通信。

    通常情况下 WCF Named Pipes are used for

    取自链接:

    [ServiceContract(Namespace = "http://example.com/Command")]
    interface ICommandService {
    
        [OperationContract]
        string SendCommand(string action, string data);
    
    }
    
    class CommandClient {
    
        private static readonly Uri ServiceUri = new Uri("net.pipe://localhost/Pipe");
        private static readonly string PipeName = "Command";
        private static readonly EndpointAddress ServiceAddress = new EndpointAddress(string.Format(CultureInfo.InvariantCulture, "{0}/{1}", ServiceUri.OriginalString, PipeName));
        private static readonly ICommandService ServiceProxy = ChannelFactory<ICommandService>.CreateChannel(new NetNamedPipeBinding(), ServiceAddress);
    
        public static string Send(string action, string data) {
            return ServiceProxy.SendCommand(action, data);
        }
    }
    
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    class CommandService : ICommandService {
        public string SendCommand(string action, string data) {
            //handling incoming requests
        }
    }
    static class CommandServer {
    
        private static readonly Uri ServiceUri = new Uri("net.pipe://localhost/Pipe");
        private static readonly string PipeName = "Command";
    
        private static CommandService _service = new CommandService();
        private static ServiceHost _host = null;
    
        public static void Start() {
            _host = new ServiceHost(_service, ServiceUri);
            _host.AddServiceEndpoint(typeof(ICommandService), new NetNamedPipeBinding(), PipeName);
            _host.Open();
        }
    
        public static void Stop() {
            if ((_host != null) && (_host.State != CommunicationState.Closed)) {
                _host.Close();
                _host = null;
            }
        }
    }
    
        2
  •  1
  •   Science_Fiction    12 年前

    你能不能不仅仅有一个工作应用程序,你启动它并开始DoAction()方法。然后使用任何进程间通信方法(如命名管道)在它们之间进行通信。

    这很好地解释了这一点, Anonymous pipes 与我提到的命名管道相反。

    匿名管道提供的功能比命名管道少,但也需要更少的开销。您可以使用匿名管道来简化本地计算机上的进程间通信。不能使用匿名管道通过网络进行通信。