2012-09-09 52 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個簡單行替換爲非常複雜的代碼? –