【发布时间】:2012-02-06 14:14:38
【问题描述】:
以下代码正在生成警告。问题是我们需要管道来读写。如何安全地处理管道?
警告:CA2202:Microsoft.Usage:对象“管道”可以在方法“ClientConnection.qaz()”中多次处理。为避免生成 System.ObjectDisposedException,您不应在一个对象上多次调用 Dispose。: Lines: 465
void qaz()
{
const string THIS_SERVER = ".";
using (NamedPipeClientStream pipe = new NamedPipeClientStream(THIS_SERVER, this.Name,
PipeDirection.InOut,
PipeOptions.None))
{
using (StreamReader sr = new StreamReader(pipe))
{
string message = sr.ReadLine();
using (StreamWriter sw = new StreamWriter(pipe))
{
sw.WriteLine("ACK received");
}
}
}
}
您需要 Visual Studio 代码分析才能看到这些警告(这些不是 c# 编译器警告)。
问题在于 StreamReader sr 和 StreamWriter sw 都 Dispose 的对象管道。
【问题讨论】: