1. 程式人生 > >C# 兩個進程之間通訊(管道通信 )

C# 兩個進程之間通訊(管道通信 )

click 失敗 != else iss nbsp obj c# cal

#region 客戶端
NamedPipeClientStream pipeClient =
new NamedPipeClientStream("localhost", "testpipe", PipeDirection.InOut, PipeOptions.Asynchronous, TokenImpersonationLevel.None);
StreamWriter sw = null;

private void Form1_Load(object sender, EventArgs e)
{
try
{
pipeClient.Connect(5000);
sw = new StreamWriter(pipeClient);
sw.AutoFlush = true;
}
catch (Exception ex)
{
MessageBox.Show("連接建立失敗,請確保服務端程序已經被打開。");
this.Close();
}
}

private void button1_Click(object sender, EventArgs e)
{
if (sw != null)
{
sw.WriteLine(this.richTextBox1.Text);
}
else
{
MessageBox.Show("未建立連接,不能發送消息。");
}
}

#endregion

#region 服務端



NamedPipeServerStream pipeServer =
new NamedPipeServerStream("testpipe", PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);

private void Form1_Load(object sender, EventArgs e)
{
ThreadPool.QueueUserWorkItem(delegate
{
pipeServer.BeginWaitForConnection((o) =>
{
NamedPipeServerStream pServer = (NamedPipeServerStream)o.AsyncState;
pServer.EndWaitForConnection(o);
StreamReader sr = new StreamReader(pServer);
while (true)
{
this.Invoke((MethodInvoker)delegate { listView1.Items.Add(sr.ReadLine()); });
}
}, pipeServer);
});
}


#endregion

C# 兩個進程之間通訊(管道通信 )