2012-02-06 69 views
3

以下代码正在生成警告。问题是我们需要管道读取和写入。我怎样才能安全地处理管道?丢弃具有2个流的对象

警告:CA2202:Microsoft.Usage:对象'pipe'可以在方法'ClientConnection.qaz()'中多次处置。为了避免产生System.ObjectDisposedException你不应该调用Dispose不止一次对象:线路上: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对象管的两端丢弃。

回答

1

您应该iMHO忽略警告并将其标记。 StreamReader是imho不应该处理内部流。它并不拥有它。

1

你在做什么应该'安全'处理管道。我通常发现这个编译器的警告非常令人厌烦,对象应该很乐意多次处置,事实上,对于NamedPipeClientStream的实例这样做可以。我会建议在这里忽略这个警告。

的信息 - 克服这一警告的方式是write your own try, finally blocks而不是使用using结构:

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(); 
    } 
} 
+1

是的,忽略CA2202。这是一个愚蠢的警告。 – porges 2012-02-07 11:03:59

+1

sr和sw都会处理对象管道,所以仍然存在问题。 – David 2012-02-07 11:05:38

0

试试下面这个例子在MSDN上如何处理这种情况:

http://msdn.microsoft.com/en-us/library/ms182334.aspx

这是你的管道被丢弃两次,我不认为这与你使用StreamReader和StreamWriter的事实有什么关系。或者它也可以,并且您可以在类似的例子上扩展。