处理具有 2 个流的对象
以下代码生成警告。问题是我们需要管道来读取和写入。如何安全地处理管道?
警告:CA2202:Microsoft.Usage:对象“pipe”可以在方法“ClientConnection.qaz()”中多次处置。为了避免生成 System.ObjectDisposeException,您不应在一个对象上多次调用 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 都处理对象管道。
The following code is generating a warning. The problem is that we need the pipe to both read and write. How can I safely dispose of the pipe?
warning : CA2202 : Microsoft.Usage : Object 'pipe' can be disposed more than once in method 'ClientConnection.qaz()'. To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.: 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");
}
}
}
}
You need Visual Studio Code Analysis to see these warnings (these are not c# compiler warnings).
The problem is that the StreamReader sr and the StreamWriter sw both Dispose of the object pipe.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
iMHO 您应该忽略该警告并标记它。 StreamReader 恕我直言不应该处理内部流。它不拥有它。
You should iMHO ignore the warning and flag it. StreamReader is imho not supposed to dispose the inner stream. It does not own it.
您正在做的事情应该“安全”地处理管道。我通常发现这个编译器警告非常令人讨厌,对象应该很乐意被多次处理,实际上,对于
NamedPipeClientStream
的实例这样做是可以的。我建议在这里忽略这个警告。有关信息 - 克服此警告的方法是编写自己的尝试,最后阻止< /a> 而不是使用
using
结构:What you are doing should 'safely' dispose of the pipe. I generally find this compiler warning highly irksome, objects should be happy to be disposed multiple times and indeed it is fine to do so for an instance of
NamedPipeClientStream
. I would suggest ignoring this warning here.For information - the way to overcome this warning is to write your own try, finally blocks rather than using the
using
construct:查看 MSDN 上的示例,了解如何处理这种情况:
http://msdn。 microsoft.com/en-us/library/ms182334.aspx
这是你的管道被处理了两次,我认为这与你同时使用这两个管道这一事实没有任何关系StreamReader 和 StreamWriter。或者也许确实如此,您可以类似地扩展该示例。
Check out this example on MSDN on how to handle this case:
http://msdn.microsoft.com/en-us/library/ms182334.aspx
It is your pipe that is being disposed of twice, and I don't think this has anything to do with the fact that you're using both StreamReader and StreamWriter. Or perhaps it does, and you can just extend on the example similarly.