473,387 Members | 1,698 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

HttpWebRequest and IDisposable

Hi,

The following code works:

HttpWebRequest objRequest = null;
try
{
HttpWebRequest objRequest =
(HttpWebRequest)WebRequest.Create("http://www.microsoft.com");
using (HttpWebResponse objResponse =
(HttpWebResponse)objRequest.GetResponse())
{
// do something...
}
}
catch
{
throw;
}
finally
{
if (objWebRequest != null)
{
objWebRequest = null;
}
}

However, the following code doesn't work:

using (HttpWebRequest objRequest =
(HttpWebRequest)WebRequest.Create("http://www.microsoft.com"))
{
using (HttpWebResponse objResponse =
(HttpWebResponse)objRequest.GetResponse())
{
// do something...
}
}

because HttpWebRequest is not implicitly convertible to IDisposable.

I'm curious to know if there is a way to use HttpWebRequest with the
"using" - just for my own interest, really...

Any assistance gratefully received.

Mark
Dec 10 '06 #1
12 7918
(Following relates to all general variable usage; not specifically to
web-request)

Well, what do you think your code does?

catch {
throw;
}

Does nothing, as it would have been thrown anyway... so that leaves the
finally:

finally
{
if (objWebRequest != null)
{
objWebRequest = null;
}
}

Interestingly, because you read the variable (in the test), this
technically *extends* the lifetime of the variable. Otherwise it would
be eligible for collection earlier. I guess it all depends on whether
objWebRequest is a field (scoped by the class) or a variable (scoped by
the method). If a field, fine: just remove the catch; if a variable,
then just let it go out of scope; it will actually be avaiable for GC
as soon as your last "read". In a garbage collected world, the "using"
and "finally" patterns are mainly for timely disposal of resources. The
above looks more like COM / VB6, but you don't need this with C#
variables.

Marc

Dec 10 '06 #2
Hi Mark,

<snip>
However, the following code doesn't work:

using (HttpWebRequest objRequest =
(HttpWebRequest)WebRequest.Create("http://www.microsoft.com"))
{
using (HttpWebResponse objResponse =
(HttpWebResponse)objRequest.GetResponse())
{
// do something...
}
}

because HttpWebRequest is not implicitly convertible to IDisposable.

I'm curious to know if there is a way to use HttpWebRequest with the
"using" - just for my own interest, really...
I think it's strange that WebRequest doesn't implement IDisposable since it
can create a Stream, which does implement IDisposable. Unfortunately, there
is no way for you to use the "using" statement with this class, although you
probably shouldn't worry about that anyway.

Instead, you may want to use WebClient, which is IDisposable:

using (WebClient client = new WebClient())
{
using (Stream stream = client.OpenRead(url))
{
// etc.
}
}

--
Dave Sexton
Dec 10 '06 #3
"Marc Gravell" <ma**********@gmail.comwrote in message
news:11**********************@n67g2000cwd.googlegr oups.com...
I guess it all depends on whether objWebRequest is a field
(scoped by the class) or a variable (scoped by the method).
It has nothing whatsoever to do with that at all - did you actually*read* my
original post...?

Dave Sexton understood it and replied accordingly - you might want to have a
read at his...
Dec 10 '06 #4
"Dave Sexton" <dave@jwa[remove.this]online.comwrote in message
news:ev**************@TK2MSFTNGP04.phx.gbl...
I think it's strange that WebRequest doesn't implement IDisposable since
it can create a Stream, which does implement IDisposable.
I was / am of that opinion too - hence my original post...
Unfortunately, there is no way for you to use the "using" statement with
this class,
That's what I thought - thanks for the clarification.
although you probably shouldn't worry about that anyway.
Indeed not - like I said, I merely posted the question for my own interest,
not because I had some burning need to use "using" with HttpWebRequest...
:-)

I find that by now, after quite a few years of working with the .NET
Framework, most of it makes reasonably intuitive sense, so when I come
across something like this which seems unusual, I'm naturally curious about
it...
Instead, you may want to use WebClient, which is IDisposable:

using (WebClient client = new WebClient())
{
using (Stream stream = client.OpenRead(url))
{
// etc.
}
}
That seems like a good suggestion - so, am I right in thinking that
WebClient performs the functions of both HttpWebRequest and
HttpWebResponse...?
Dec 10 '06 #5
Yes,
WebClient does, but it's a wrapper over the whole mechanism designed to
simplify and doesn't provide access to all the lower-level "stuff" that's in
HttpWebRequest and HttpWebResponse.
Peter

--
Co-founder, Eggheadcafe.com developer portal:
http://www.eggheadcafe.com
UnBlog:
http://petesbloggerama.blogspot.com


"Mark Rae" wrote:
"Dave Sexton" <dave@jwa[remove.this]online.comwrote in message
news:ev**************@TK2MSFTNGP04.phx.gbl...
I think it's strange that WebRequest doesn't implement IDisposable since
it can create a Stream, which does implement IDisposable.

I was / am of that opinion too - hence my original post...
Unfortunately, there is no way for you to use the "using" statement with
this class,

That's what I thought - thanks for the clarification.
although you probably shouldn't worry about that anyway.

Indeed not - like I said, I merely posted the question for my own interest,
not because I had some burning need to use "using" with HttpWebRequest...
:-)

I find that by now, after quite a few years of working with the .NET
Framework, most of it makes reasonably intuitive sense, so when I come
across something like this which seems unusual, I'm naturally curious about
it...
Instead, you may want to use WebClient, which is IDisposable:

using (WebClient client = new WebClient())
{
using (Stream stream = client.OpenRead(url))
{
// etc.
}
}

That seems like a good suggestion - so, am I right in thinking that
WebClient performs the functions of both HttpWebRequest and
HttpWebResponse...?
Dec 10 '06 #6
"Peter Bromberg [C# MVP]" <pb*******@yahoo.nospammin.comwrote in message
news:2B**********************************@microsof t.com...
WebClient does, but it's a wrapper over the whole mechanism designed to
simplify and doesn't provide access to all the lower-level "stuff" that's
in
HttpWebRequest and HttpWebResponse.
Thanks for that.
Dec 10 '06 #7
did you actually*read* my original post...?
Yes thanks very much for asking. You said (essentially) "this works". I
was observing that it may well work, but it achieves nothing.

Marc

Dec 10 '06 #8
Additional:
I think it's strange that WebRequest doesn't implement IDisposable since it
can create a Stream, which does implement IDisposable.

Just because something is capable of creating and returning an
IDisposable object does not imply that it is *itself* IDisposable. Any
objects created from this class should, of course, be disposed
correctly.
I have run reflector over WebClient, and even in this case it only
picks up IDisposable as an arftifact of the base Component class - it
doesn't actually provide any Dispose() logic of its own. Of course, I
would still be "using" WebClient.

The *very* curious thing (to turn this all on its head) is that
HttpWebRequest *does* have some IDisposable fields - a few internal
streams and a timer (possibly more; stopped looking). Unless these are
all guaranteed to be cleaned up before leaving encapsulating methods,
you would *expect* HttpWebRequest to be disposable, and hence the
original "why doesn't this work" would be completely valid (and
WebClient would have something interesting to do in *its* Dispose()
method). All very interesting.

My original point, however, still stands: setting something to null is
a very different beast to Dispose()ing it; if it isn't IDisposable,
then it doesn't need to be Dispose()d, so you can't be "using" it.

Marc

Dec 10 '06 #9
"Marc Gravell" <ma**********@gmail.comwrote in message
news:11**********************@n67g2000cwd.googlegr oups.com...
setting something to null is a very different beast to Dispose()ing it;
That's right.
if it isn't IDisposable, then it doesn't need to be Dispose()d,
Er, surely if it isn't IDisposable, then it *can't* be Dispose()d,
irrespective of whether it needs to be or not...???
so you can't be "using" it.
Er, right again... And precisely because HttpWebRequest isn't IDisposable, I
wasn't "using" it, hence the reason I was explicitly setting it to null in
finally{...}

My original post centred on my surprise that HttpWebRequest *isn't*
IDisposable...
Dec 10 '06 #10
Hi Marc,
>I think it's strange that WebRequest doesn't implement IDisposable since
it
can create a Stream, which does implement IDisposable.

Just because something is capable of creating and returning an
IDisposable object does not imply that it is *itself* IDisposable
It had seemed obvious to me, and still does, that HttpWebRequest should
implement IDisposable not because it simply may "return" a Stream, but
because it "composites" one, and Stream is certainly IDisposable. I used
the term "create", not "return", but in hindsight I should have wrote
"composites" :)

The point being that HttpWebRequest manages the lifetime of the Stream.
GetRequestStream is available, but doesn't have to be called. A Stream is
created to make the request, but because it's still referenced by the
HttpWebRequest object for when GetResponse is called, it doesn't make sense
to me that the caller should be responsible to dispose of the Stream. How
should the caller know when HttpWebRequest is done using the Stream? After
all, the implementation details shouldn't be known to the caller but this
pattern implies them, such as that GetResponse must ensure that the entire
Stream is read before returning to the caller or else disposing it early
would be problematic.

I hope that clears up :)

<snip>

Interesting, about the internals of WebClient. I bet the developers
implemented IDisposable for future use (since HttpWebRequest should
implement IDisposable). I wonder if they tried to implement it and went,
"Un oh. Who designed HttpWebRequest?" :)

--
Dave Sexton
Dec 10 '06 #11
My original post centred on my surprise that HttpWebRequest *isn't*
IDisposable...
I've just re-read the OP very carefully, and if this was your intent it
isn't exactly very clear... but for the sake of agreement I'll take
that at face value... ;-p

But I think we (the 3 of us, at least) all now agree that it *should*
work the way you suggest, but it can't. It wouldn't be the first or
last such, but it was an intersting question.

Marc

Dec 11 '06 #12
"Marc Gravell" <ma**********@gmail.comwrote in message
news:11**********************@l12g2000cwl.googlegr oups.com...
>My original post centred on my surprise that HttpWebRequest *isn't*
IDisposable...

I've just re-read the OP very carefully, and if this was your intent it
isn't exactly very clear... but for the sake of agreement I'll take
that at face value... ;-p
In which case, that's my fault, and I apologise for the lack of clarity...
But I think we (the 3 of us, at least) all now agree that it *should*
work the way you suggest, but it can't. It wouldn't be the first or
last such, but it was an intersting question.
Maybe it will change in the next version...:-)
Dec 11 '06 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: VladG | last post by:
The following code being repeated in a loop sends keep-alive at frst iteration only. So I quickly run out of ports (all are in time_wait state) Why? // create the web request to get the remote...
5
by: Robert Heuvel | last post by:
Hi, this is what I did: public struct SWaitCursor:IDisposable { public SWaitCursor (int i) { Cursor.Current = Cursors.WaitCursor; } void System.IDisposable.Dispose() { Cursor.Current =...
1
by: mwieder | last post by:
The following code hangs at the GetRequestStream after a few loops of succesful execution: while (true) { HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(new Uri(strUri)); ...
4
by: Helge Jensen | last post by:
In C# 2.0 System.IO.Stream is declared as: public class Stream: ..., IDisposable { ... public void Dispose(); public void Dispose(bool); IDisposable.Dispose(); } Which must be a...
10
by: Basel | last post by:
Hi All, I'm opening a number of threads, and each thread generates http requests using HttpWebRequest. How to make each thread open only 1 connection ? I tried to set a unique...
4
by: phl | last post by:
hi, My question is: 1. To avoid possible memory leaks, when you use this pattern, after you have dealth with the unmanaged resources and before you take your object off the finalize queue,...
6
by: Water Cooler v2 | last post by:
I heard from someone that we must not implement IDisposable for all classes. Can someone please tell me: 1. the reason why we must not implement IDisposable for all the classes we write. 2....
11
by: Mark Rae | last post by:
Hi, Following on from the recent thread about why HttpWebRequest doesn't implement the IDisposable interface, I got to wondering whether people make their custom classes inherit IDisposable or...
5
by: Glenn | last post by:
Hi I'm trying to building something to check the availability of a web page. The code is using a HttpWebRequest, bypassing our proxy server and hitting both HTTP/HTTPS pages. Initially I get...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.