使用网络客户端时,应用程序在启动时冻结
本文关键字:启动 冻结 应用程序 网络 客户端 | 更新日期: 2023-09-27 18:19:39
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 处理程序中时,结果相同。
问题是如何防止启动时冻结?
我见过由 WebClient.Proxy
属性引起的类似的 UI 挂起问题:
属性标识通信的 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);
}
你能尝试使用线程安全的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); });
}