C#管道操作取消作为服务运行时的异常
我正在开发一个windows服务应用程序,遇到了一个有关命名管道服务器的问题。 服务应用程序有一个命名管道服务,以便GUI与之通信,GUI有一个命名管道客户端 当我运行我的应用程序的控制台版本(相同的代码,但在控制台项目中初始化)时,一切正常,但当我运行应用程序的服务版本(使用安装项目或使用VS unistallUtil.exe安装)时,我收到以下错误:C#管道操作取消作为服务运行时的异常,c#,exception,service,pipe,C#,Exception,Service,Pipe,我正在开发一个windows服务应用程序,遇到了一个有关命名管道服务器的问题。 服务应用程序有一个命名管道服务,以便GUI与之通信,GUI有一个命名管道客户端 当我运行我的应用程序的控制台版本(相同的代码,但在控制台项目中初始化)时,一切正常,但当我运行应用程序的服务版本(使用安装项目或使用VS unistallUtil.exe安装)时,我收到以下错误: System.OperationCanceledException: The operation was canceled. at Sy
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
当我启动服务时,甚至没有尝试将客户端连接到服务时,就会发生此错误。以下是我的PipeServer类:
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
}
关于(我所理解的)你遇到的同一个问题进行了讨论
Windows将为已退出的线程完成所有重叠的I/O,错误操作被中止
IAsyncResult不一定意味着重叠I/O,但它是一个
自然拟合,这似乎是命名管道使用的方法
在这种情况下,我建议让主线程创建
命名管道;这对于命名管道服务器(具有单独的
仅用于创建命名管道的线程不可用)
谢谢你的链接,帕特里克。由于我必须使用一个线程来启动PipeService(Windows服务程序需要一个线程来启动服务,因为它需要应用程序在不到5秒钟内做出响应),因此我想出了一个解决问题的方法。我会在彻底测试后发布我的解决方案。