【问题标题】:Disposing of an object that has 2 streams处理具有 2 个流的对象
【发布时间】: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 的对象管道。

【问题讨论】:

    标签: c# stream


    【解决方案1】:

    您应该 iMHO 忽略警告并标记它。 StreamReader 恕我直言不应该处理内部流。它不拥有它。

    【讨论】:

      【解决方案2】:

      您正在做的事情应该“安全地”处理掉管道。我通常发现这个编译器警告非常令人讨厌,对象应该很乐意被多次处理,而且对于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();
        }
      }
      

      【讨论】:

      • sr和sw都会dispose对象管道,所以还是有问题。
      【解决方案3】:

      查看 MSDN 上的这个例子,了解如何处理这种情况:

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

      您的管道被处理了两次,我认为这与您同时使用 StreamReader 和 StreamWriter 的事实没有任何关系。或者可能确实如此,您可以类似地扩展示例。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-07-14
        • 2020-09-10
        • 1970-01-01
        • 2013-07-21
        • 2017-02-07
        • 2019-12-10
        • 2023-03-27
        • 2011-03-30
        相关资源
        最近更新 更多