C# 处理具有2个流的对象
以下代码正在生成警告。问题是我们需要管道来读写。如何安全地处理管道 警告:CA2202:Microsoft。用法:可以在方法“ClientConnection.qaz()”中多次释放对象“管道”。为了避免生成System.ObjectDisposedException,您不应该对一个对象多次调用Dispose。:Lines:465 您需要Visual Studio代码分析来查看这些警告(这些不是c#编译器警告)C# 处理具有2个流的对象,c#,stream,C#,Stream,以下代码正在生成警告。问题是我们需要管道来读写。如何安全地处理管道 警告:CA2202:Microsoft。用法:可以在方法“ClientConnection.qaz()”中多次释放对象“管道”。为了避免生成System.ObjectDisposedException,您不应该对一个对象多次调用Dispose。:Lines:465 您需要Visual Studio代码分析来查看这些警告(这些不是c#编译器警告) 问题是StreamReadersr和StreamWritersw都会处理对象管道。您
问题是StreamReadersr和StreamWritersw都会处理对象管道。您应该忽略警告并将其标记。StreamReader不应该处理内部流。它不拥有它。您所做的应该“安全”处理管道。我通常觉得这个编译器警告非常令人讨厌,对象应该乐于被多次处理,而且对于
NamedPipeClientStream
的实例来说,这样做确实很好。我建议忽略这个警告
仅供参考-克服此警告的方法是,而不是使用的构造:
NamedPipeClientStream pipe = null;
try
{
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");
}
}
pipe = null;
}
finally
{
if (pipe != null)
{
pipe.Dispose();
}
}
查看MSDN上关于如何处理此案例的示例:
是你的管道被处理了两次,我认为这与你同时使用StreamReader和StreamWriter的事实无关。或者可能是这样,您可以对示例进行类似的扩展。sr和sw都将处理对象管道,因此仍然存在问题。
NamedPipeClientStream pipe = null;
try
{
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");
}
}
pipe = null;
}
finally
{
if (pipe != null)
{
pipe.Dispose();
}
}