I am developing a windows service application and I’m running into a problem concerning named pipe server.
The service application has a named pipe service, in order for the GUI to communicate with it – and the GUI has a named pipe client.
When I run the console version of my app (same code but initialized in a console project), everything works fine, but when I run the service version of the app (either installed using setup project or using VS unistallUtil.exe) I get this error:
System.OperationCanceledException: The operation was canceled.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.Pipes.NamedPipeServerStream.EndWaitForConnection(IAsyncResult asyncResult)
at Common.PipeCommunication.SomePipeServer.ClientConnected(IAsyncResult ar) in SomePipeServer.cs:line 80
This error occurs when I start the service, not even attempting to connect the client to it. Here is my PipeServer Class:
public class SomePipeServer
{
#region PRIVATE VARIABLES
private string _pipeName = "SomePipeServer";
private NamedPipeServerStream _pipeServer;
private IAsyncResult _connectRequest;
private byte[] oBuffer;
#endregion
#region PUBLIC VARIABLES
public event EventHandler MsgReceived;
#endregion
#region PUBLIC METHODS
public SomePipeServer()
{
oBuffer = new byte[4096];
}
public void Start()
{
try
{
_pipeServer = new NamedPipeServerStream(
_pipeName, PipeDirection.InOut, -1,
PipeTransmissionMode.Message,
PipeOptions.Asynchronous);
_connectRequest = _pipeServer.BeginWaitForConnection(
ClientConnected, null);
}
catch (Exception ex)
{
...
}
}
public void Stop()
{
try
{
_connectRequest = null;
if (_pipeServer == null)
return;
if (_pipeServer.IsConnected)
_pipeServer.Disconnect();
//_pipeServer.Close();
}
catch (Exception ex)
{
...
}
}
#endregion
#region PRIVATE METHODS
private void ClientConnected(IAsyncResult ar)
{
try
{
if (ar != null)
{
_pipeServer.EndWaitForConnection(ar); //line 80
_connectRequest = null;
_connectRequest = _pipeServer.BeginRead(oBuffer, 0, 4096,
ClientMessage, null);
}
}
catch (Exception ex)
{
...
}
}
private void ClientMessage(IAsyncResult ar)
{
try
{
if (ar != null)
{
_pipeServer.EndRead(ar);
string message = System.Text.ASCIIEncoding.ASCII.GetString(oBuffer).Trim(new char[] { '\0', ' ' });
message = message.Replace(Environment.NewLine, " ").TrimEnd();
OnReceive(message);
_connectRequest = null;
//_connectRequest = _pipeServer.BeginRead(oBuffer, 0, 4096,
// new AsyncCallback(ClientMessage), null);
//_pipeServer.Disconnect();
//_pipeServer.BeginWaitForConnection(ClientConnected, null);
Stop();
Start();
}
}
catch (Exception ex)
{
...
}
}
private void OnReceive(string in_msg)
{
if (MsgReceived != null)
{
MsgReceived(in_msg, EventArgs.Empty);
}
}
#endregion
}
There is a discussion on this MSDN page about (what I’ve understood) the same problem that you have.