Pablo
Pablo

Reputation: 29519

App is freezing on startup when using WebClient

private void Form1_Shown(object sender, EventArgs e)
{
    ...
    WebClient webClient = new WebClient();
    webClient.Encoding = Encoding.UTF8;
    webClient.Headers.Add(@"Content-Type: application/json; charset=utf-8");
    webClient.UploadStringAsync(new Uri(Config.MessagingURL), "POST", json);
    webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(webClient_UploadStringCompleted);
}

Above lines are rendering application not responsive for few seconds. Also the main form is drawn partially. After few seconds all is fine again. I thought request and response are happening in separate thread, which doesn't look to be a case, unless I am doing something wrong. Same result is when I put this code in OnLoad handler of main form.

Question is how to prevent freezing on startup?

Upvotes: 2

Views: 138

Answers (2)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

I have seen similar issues of UI hang caused by the WebClient.Proxy property:

The Proxy property identifies the IWebProxy instance that communicates with remote servers on behalf of this WebClient object. The proxy is set by the system using configuration files and the Internet Explorer Local Area Network settings.

Try explicitly setting it to null before making the request (i am assuming you are not making this request behind a proxy):

private void Form1_Shown(object sender, EventArgs e)
{
    WebClient webClient = new WebClient();
    webClient.Proxy = null;

    webClient.Encoding = Encoding.UTF8;
    webClient.Headers.Add(@"Content-Type: application/json; charset=utf-8");

    webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(webClient_UploadStringCompleted);
    webClient.UploadStringAsync(new Uri(Config.MessagingURL), "POST", json);
}

Upvotes: 2

Vimal CK
Vimal CK

Reputation: 3563

Can you try using Task.Factory.StartNew which is thread safe

private void Form1_Shown(object sender, EventArgs e)
{
     WebClient webClient = new WebClient();
     webClient.Encoding = Encoding.UTF8;
     webClient.Headers.Add(@"Content-Type: application/json; charset=utf-8");
     webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(webClient_UploadStringCompleted);
     Task.Factory.StartNew(() => { webClient.UploadDataAsync(new Uri("your uri"),"POST",json); });
}

Upvotes: 0

Related Questions