473,804 Members | 3,557 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

HttpWebRequest and IDisposable

Hi,

The following code works:

HttpWebRequest objRequest = null;
try
{
HttpWebRequest objRequest =
(HttpWebRequest )WebRequest.Cre ate("http://www.microsoft.c om");
using (HttpWebRespons e objResponse =
(HttpWebRespons e)objRequest.Ge tResponse())
{
// do something...
}
}
catch
{
throw;
}
finally
{
if (objWebRequest != null)
{
objWebRequest = null;
}
}

However, the following code doesn't work:

using (HttpWebRequest objRequest =
(HttpWebRequest )WebRequest.Cre ate("http://www.microsoft.c om"))
{
using (HttpWebRespons e objResponse =
(HttpWebRespons e)objRequest.Ge tResponse())
{
// 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 7989
(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.Cre ate("http://www.microsoft.c om"))
{
using (HttpWebRespons e objResponse =
(HttpWebRespons e)objRequest.Ge tResponse())
{
// 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**********@g mail.comwrote in message
news:11******** **************@ n67g2000cwd.goo glegroups.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******** ******@TK2MSFTN GP04.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******** ******@TK2MSFTN GP04.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*******@yaho o.nospammin.com wrote in message
news:2B******** *************** ***********@mic rosoft.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**********@g mail.comwrote in message
news:11******** **************@ n67g2000cwd.goo glegroups.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

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

Similar topics

6
14234
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 stream HttpWebRequest requestToCrk = (HttpWebRequest)WebRequest.Create( url ); requestToCrk.Method = "POST"; requestToCrk.KeepAlive = true; requestToCrk.ContentType = "application/octet-stream";
5
3190
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 = Cursors.Default;
1
5524
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)); //add headers here httpRequest.Method = "POST"; httpRequest.Referer = strReferer;
4
2036
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 design-blunder, if not a 100-year sleep. It prevents
10
20500
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 ConnectionGroupName for each thread, but after some time the number of connections exceeds the number of threads (I see more than thousand connection while only 100 threads are running). Thank you
4
3334
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, how are you sure that your managed object resources are completely freed up of resources it's might be using? In my case below I have a private bool variable. Are there any other managed resource that you might need to explicitly free up in
6
3587
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. what is the correct way of implementing IDisposable.Dispose? 3. what is the preferred way, if there is one over the other, of calling the Dispose method on an object that implements IDisposable. Is it the way that uses the "using(object){}" construct...
11
2324
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 not as a general rule, or only under certain circumstances... Since it's an easy enough thing to do (http://msdn2.microsoft.com/en-us/library/system.idisposable.aspx), is there any good reason not to make every custom class IDisposable, the same...
5
3517
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 a HTTP response code of 200. After the second or third attempt at hitting the same page over a period of a couple of minutes, I get a timeout. Note that I'm creating a fresh HttpWebRequest each time I hit the web page.
0
10583
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10337
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10323
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10082
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7622
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5525
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5654
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3822
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2995
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.