2012-09-09 49 views
2

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

我想要做的是,在任何致电worker()的新实例中,都会在新进程中打开一个新实例,以便我可以在任务管理器中看到很多worker.exe。

我以前用vb com包装做过,但现在我只想在C#和没有COM的情况下做到这一点,
我可以以最基本的方式做到这一点吗?

实例类:

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(); 
+0

使用.Net Remoting。 – Asti

+0

你能解释一下你为什么要这样工作吗?可能有更简单的选项来实现相同的结果。 – Maarten

回答

3

你可以在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; 
     } 
    } 
} 
1

你能不只是有你火了起来,并开始DoAction()方法的工作者应用。然后使用任何进程间通信方法(如命名管道)在它们之间进行通信。

这解释得很好,Anonymous pipes,而不是像我提到的命名管道。

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

+0

你能举个例子吗? –

+0

更新,这有帮助吗? –

+0

为什么这需要如此复杂?如何将VB中使用COM的10个简单行替换为非常复杂的代码? –