Dgameman1 Dgameman1 - 3 months ago 7
C# Question

Any negatives of wrapping all code inside Using Webclient?

using (WebClient client= new WebClient())
{
//specific webclient stuff
}

using (WebClient client= new WebClient())
{
Textbox1.text = "hey";
//specific webclient stuff
MessageBox.show("Random");
}


Is there any performance difference between those 2?

Is it alright to have not
webclient
related stuff inside a
using webclient
?

Answer

It really doesn't make too much of a difference for WebClient. The trick is to generally try to use an dispose a resource as quickly as possible.

I tend to do this kind of a thing:

public static class WebClientEx
{
    public static T Using<T>(this Func<WebClient, T> factory)
    {
        using (var wc = new WebClient()
        {
            return factory(wc);
        }
    }
}

Then I can call code like this:

Textbox1.text = "hey";
string text = WebClientEx.Using(wc => wc.DownloadString(@"url"));
MessageBox.show(text);

Or even:

Func<WebClient, string> fetch = wc => wc.DownloadString(@"url");

Textbox1.text = "hey";
string text = fetch.Using();
MessageBox.show(text);

This minimizes the time that the WebClient is created and it keeps the code that it is in fairly neat.

Comments