HttpWebRequest中的ObjectDisposedException

时间:2017-04-28 13:07:29

标签: c# .net httpwebrequest compact-framework webrequest

我在Compact框架中创建一个Web请求

HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("Url");

using (StreamWriter streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
     streamWriter.Write("body");

using (HttpWebResponse response = httpWebRequest.GetResponse() as HttpWebResponse)
using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
{
     string json = streamReader.ReadToEnd();
}

我得到ObjectDisposedException。 我责怪response.GetResponseStream()这个错误,但这段代码出了什么问题?

堆栈跟踪

System.ObjectDisposedException 
ObjectDisposedException-   at System.Threading.Timer.throwIfDisposed()
   at System.Threading.Timer.Change(UInt32 dueTime, UInt32 period)
   at System.Threading.Timer.Change(Int32 dueTime, Int32 period)
   at System.Net.HttpWebRequest.ConnectionClient.Read(Byte[] data, Int32 offset, Int32 length)
   at System.Net.HttpReadStream.NetworkRead(Byte[] data, Int32 offset, Int32 length)
   at System.Net.ContentLengthReadStream.doRead(Byte[] data, Int32 offset, Int32 length)
   at System.Net.HttpReadStream.ReadToDrain(Byte[] buffer, Int32 offset, Int32 length)
   at System.Net.HttpReadStream.doClose()
   at System.Net.ContentLengthReadStream.doClose()
   at System.Net.HttpReadStream.Finalize()

1 个答案:

答案 0 :(得分:0)

我怀疑是因为你处理了StreamWriter,而HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("Url"); StreamWriter streamWriter; try { streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) streamWriter.Write("body"); using (HttpWebResponse response = httpWebRequest.GetResponse() as HttpWebResponse) using (StreamReader streamReader = new StreamReader(response.GetResponseStream())) { string json = streamReader.ReadToEnd(); } } finally { streamWriter.Dispose(); } 又处理了请求流。这对请求本身有什么影响,我不知道,但我会猜测事情正在发生变化。

您可以随时使用Reflector深入了解BCL以确切了解会发生什么,但尝试这样的测试可能更快更容易:

#haml/slim
= cell(PopupLoginCell, my_model, current_user: current_user)
#erb
<%= cell(PopupLoginCell, my_model, current_user: current_user) %>