In the following code
namespace ns
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string ProcessCommand(string cmd)
{
return "i got " + cmd;
}
StreamReader d_sr;
StreamWriter d_sw;
NamedPipeServerStream d_pipe;
IAsyncResult d_ar;
void Connected(IAsyncResult ar)
{
d_pipe.EndWaitForConnection(ar);
d_sw.AutoFlush = true;
while (true)
{
var cmd = d_sr.ReadLine();
if (cmd == null)
break;
var answer = ProcessCommand(cmd);
d_sw.WriteLine(answer);
}
d_pipe.Disconnect();
d_ar = d_pipe.BeginWaitForConnection(Connected, null);
}
private void Form1_Load(object sender, EventArgs e)
{
d_pipe = new NamedPipeServerStream("vatm", PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);
d_sr = new StreamReader(d_pipe);
d_sw = new StreamWriter(d_pipe);
d_ar = d_pipe.BeginWaitForConnection(Connected, null);
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
d_pipe.EndWaitForConnection(d_ar);
d_pipe.Dispose();
}
}
}
when I go to close the form, it waits in EndWaitForConnection. I'm going to tell the pipe not to wait for client anymore and abort. I tried d_pipe.Close() instead of calling EndWaitForConnection, but I get this exception at EndWaitForConnection called in Connected.
An unhandled exception of type 'System.ObjectDisposedException' occurred in System.Core.dll Additional information: Cannot access a closed pipe.
Any idea?
I changed it to this:
namespace ns
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string ProcessCommand(string cmd)
{
return "i got " + cmd;
}
StreamReader d_sr;
StreamWriter d_sw;
NamedPipeServerStream d_pipe;
IAsyncResult d_ar;
void Connected(IAsyncResult ar)
{
try
{
d_pipe.EndWaitForConnection(ar);
d_sw.AutoFlush = true;
while (true)
{
var cmd = d_sr.ReadLine();
if (cmd == null)
break;
var answer = ProcessCommand(cmd);
d_sw.WriteLine(answer);
}
d_pipe.Disconnect();
d_ar = d_pipe.BeginWaitForConnection(Connected, null);
}
catch (System.ObjectDisposedException)
{
// do nothing
}
}
private void Form1_Load(object sender, EventArgs e)
{
d_pipe = new NamedPipeServerStream("vatm", PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);
d_sr = new StreamReader(d_pipe);
d_sw = new StreamWriter(d_pipe);
d_ar = d_pipe.BeginWaitForConnection(Connected, null);
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
d_pipe.Close();
}
}
}