对于我的C#应用程序之间的双向数据交换,我使用命名管道. App-1是管道服务器,App-2是客户端. 当点击App-1中的按钮时,将执行PIPE_SERVER方法和App-1,因为服务器正在等待来自App-2的连接.第一次点击该按钮后,一切都按预期进行.App-2连接并向App-1发送数据.
在每次数据传输之后,我要处理管道服务器.我希望每次单击新按钮都会生成一个新的管道流,并且数据传输像以前一样从头开始运行.但在第二次单击该按钮后,我总是会看到"System.ObjectDisposedException:Cannot Access a Closed Pipes".在服务器端.我想我在服务器端处理pipestream时出了点问题.
服务器端(App-1)
public string test = "";
public StreamReader sr ;
public StreamWriter sw ;
public NamedPipeServerStream pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 20, 20);
public void pipe_server // executed on button click
{
CancellationTokenSource source = new CancellationTokenSource();
server_named_pipe(source.Token);
}
protected async Task server_named_pipe(CancellationToken stoppingToken)
{
PipeSecurity ps = new PipeSecurity();
System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
PipeAccessRule par = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
ps.AddAccessRule(par);
sr = new StreamReader(pipeServer);
sw = new StreamWriter(pipeServer);
try
{
var asyncResult = pipeServer.BeginWaitForConnection(PipeConnected, this);
if (asyncResult.AsyncWaitHandle.WaitOne(5000))
{
pipeServer.EndWaitForConnection(asyncResult);
// ...
}
}
catch (Exception ex)
{
//throw ex;
pipeServer.WaitForPipeDrain();
if (pipeServer.IsConnected)
{
pipeServer.Disconnect();
}
}
finally
{
if (sw != null) sw.Dispose();
if (sr != null) sr.Dispose();
pipeServer.Dispose();
}
}
}
public void PipeConnected(IAsyncResult e)
{
sw.WriteLine("Waiting");
sw.Flush();
pipeServer.WaitForPipeDrain();
test = sr.ReadLine();
using (StreamWriter sw2 = File.AppendText(CommonClass.error_path))
{
sw2.WriteLine("Named_Pipe_message: " + " " + test + Convert.ToString(DateTime.Now) + " ");
}
}