使用WebClient时,应用程序在启动时冻结

时间:2014-08-26 17:39:04

标签: c# .net winforms

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);
}

以上几行渲染应用程序几秒钟内没有响应。主要形式也部分绘制。几秒钟后,一切都很好。我认为请求和响应是在单独的线程中发生的,除非我做错了什么,否则它看起来不是一个案例。当我将此代码放在主窗体的OnLoad处理程序中时,结果相同。

问题是如何防止启动时冻结?

2 个答案:

答案 0 :(得分:2)

我已经看到了由WebClient.Proxy属性导致的类似UI挂起问题:

  

Proxy属性标识通信的IWebProxy实例   使用远程服务器代表此WebClient对象。代理是   由系统使用配置文件和Internet Explorer设置   局域网设置。

在发出请求之前尝试将其明确设置为null(我假设您没有在代理后面发出此请求):

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);
}

答案 1 :(得分:0)

您可以尝试使用线程安全的Task.Factory.StartNew

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); });
}