2012-02-28 27 views
0

不太清楚如何做到这一点,或者甚至是编程c#的正确方法。也许我需要重新思考我正在尝试做什么,但我需要一些帮助。C#重新调用当前方法

我有一个wpf应用程序,用于启动/停止服务,并使用命名管道打开端口并与服务进行通信。所以当服务需要时它可以发送消息给应用程序。我启动了一个新线程来调用位于namedPipeServerStream.WaitForConnection()中的Wait()方法。这工作正常,但当服务停止时,我发送消息到应用程序,所以它打破了WaitForConnection,但我不想杀死这个线程,我想重新激活相同的方法,并等待一个循环,直到服务再次启动。不确定最好的方法来做到这一点。

我到目前为止的代码如下。

void Wait() 
{ 
    while (!ServiceControl.ServiceRunning) 
    { 
     Thread.Sleep(250); 
     if (exitProgram == true) 
     { 
      break; 
     } 
    } 

    while (ServiceControl.ServiceRunning) 
    { 
     try 
     { 
      NamedPipeServerStream namedPipeServerStream = new NamedPipeServerStream("pipeName"); 
      namedPipeServerStream.WaitForConnection(); 
      byte[] buffer = new byte[255]; 
      namedPipeServerStream.Read(buffer, 0, 255); 
      string request = ASCIIEncoding.ASCII.GetString(buffer); 

      if (request != null) 
      { 
       if (request == "pipeExit") 
       { 
        Wait(); //Reinvoke Wait if svc calls to exit 
       } 

       else 
       { 
        //Do work on message 
       } 
      } 
      namedPipeServerStream.Close(); 
     } 
     catch (Exception){} 
    } 

    if (_opener.exitProgram == true) 
    { 
     Application.Current.Dispatcher.InvokeShutdown(); 
    } 

回答

0

你为什么不把while(!opener.exitProgram)放在你的整个Wait实现中?这样,一旦管道关闭,你就可以回到起点。

+0

哈哈,那很容易。谢谢! – Ron 2012-02-28 17:09:54