gpt4 book ai didi

c# - 使用 WebClient 时应用程序在启动时卡住

转载 作者:太空宇宙 更新时间:2023-11-03 10:40:31 32 4
gpt4 key购买 nike

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 挂起问题属性:

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.

尝试在发出请求之前将其显式设置为 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);
}

关于c# - 使用 WebClient 时应用程序在启动时卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25511926/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com