即使主叫线程没有离开使用范围,我的NetworkStream id也会被处理掉,我得到了:
"无法访问已处置的对象。
对象名称:' System.Net.Sockets.NetworkStream"
我的印象是,如果我阻止启动事件订阅的调用方法,NetworkStream将保持活动状态,我做错了什么?
using (var tcpClient = server.AcceptTcpClient())
{
using (var networkStream = tcpClient.GetStream())
{
//Edit: start of the code that was missing from my original question
using (var sr = new StreamReader(networkStream, Encoding.ASCII))
{
var someVal = Login(sr, sw);
}
//Edit: end of the code that was missing from my original question
using (var sw = new StreamWriter(networkStream, Encoding.ASCII) { AutoFlush = true })
{
someObj.BlockingCall(sw); //calling some blocking call
}
}
}
internal class SomeObj
{
private StreamWriter _sw;
private readonly ManualResetEvent _manualResetEvent;
internal SomeObj()
{
_manualResetEvent = new ManualResetEvent(false);
}
internal void BlockingCall(StreamWriter sw)
{
try
{
_sw = sw;
dataProvider.OnHighFrequencyEvent += DataProvider_OnHighFrequencyEvent;
_manualResetEvent.WaitOne(); // here it blocks
}
catch (Exception ex)
{
log.Error("Error subscribing to dataProvider", ex);
}
}
private void DataProvider_OnHighFrequencyEvent(IData data)
{
try
{
_sw.WriteLine(data.Payload); //here the exception occurs
}
catch (Exception ex)
{
// Cannot access a disposed object.\r\nObject name: 'System.Net.Sockets.NetworkStream
}
}
}
}
编辑:
正如彼得所说的那样,缺少了一些代码(以为我删除它时更容易阅读)我在上面添加了一条注释,显然这是导致问题的原因,你可以解释一下吗?为什么?它只处理StreamReader ......