Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should WebClient instances be reused in Silverlight

I'm writing a Silverlight application for Windows Phone 7 which has a class that needs to make multiple requests to WebClient.DownloadStringAsync()

Am I better off creating a new instance of WebClient for each request, or is it more efficient to initialise a single instance in a field and use that for each request (making sure to only have one request active at any one time)?

public class MainViewModel : INotifyPropertyChanged
{
    private readonly WebClient _wc;

    public MainViewModel()
    {
        _wc = new WebClient
        {
            Credentials = new NetworkCredential( "yyyyyyy", @"xxxxxx" )
        };

    }

    readonly Uri _baseUrl = new Uri( @"https://some.web.url" );

    public void GetServices()
    {
        _wc.DownloadStringCompleted += GetServicesCompleted;
        var uri = new Uri( _baseUrl, "/path" );
        _wc.DownloadStringAsync( uri );
    }

    private void GetServicesCompleted( object sender, DownloadStringCompletedEventArgs e )
    {
        _wc.DownloadStringCompleted -= GetServicesCompleted;

        string result = e.Result;

        // other logic...

        GetServiceResources();
    }

    private void GetServiceResources()
    {
        _wc.DownloadStringCompleted += GetServicesResourcesDownloaded;
        var url = new Uri( _baseUrl, "/path2" );
        _wc.DownloadStringAsync( url );
    }

    // etc
}
like image 464
David Gardiner Avatar asked Dec 14 '10 22:12

David Gardiner


1 Answers

If you're using WebClient I'd create a new one each time. I'd also use a lambda expression for the DownloadStringCompleted event as this will enable you to keep all the related logic together.
e.g.:

var wc = new WebClient();
wc.DownloadStringCompleted += (sender, e) => { GetServiceResources(); };
wc.DownloadStringAsync(new Uri("http://example.com/path", UriKind.Absolute));

This should make the code easier to read and therefore maintain.

In that your smaple code also has nested web requests (the completed event starts another request) reuse of the same client could make debugging more difficult.

Please be aware that the WebClient automatically marshalls the completed event back to the UI thread so any work you do there will block that UI thread. If your completed event does anything other than a simple update to the UI, use of HttpWebRequest is recomended instead for performance and usability issues.

I'd also recommend against making consecutive web requests if you could possibly run them in parallel or (even better) combine the logic (and response) into a single request.

like image 170
Matt Lacey Avatar answered Nov 02 '22 06:11

Matt Lacey