在使用 WebClient 期间无法使用当前应用程序

Can't use current application during using WebClient

我试图在不询问用户 windows 应用程序的情况下更新一些数据,但是当我尝试下载时,应用程序无法使用,控件也不可触摸。

代码:

using (WebClient client = new WebClient {Encoding = System.Text.Encoding.UTF8})
{
string url = "http://domain_name.com/api/getSomeData";

res = client.DownloadString(url);
}

这很可能发生,因为您正在 UI 线程上执行代码。当您的 UI 线程繁忙时,它无法发送 window 消息,例如来自鼠标或键盘的输入事件。您的选择是:

  1. 运行 此代码在单独的线程上。

  2. 使用异步技术,例如 WebClient.DownloadStringAsync 或 DownloadStringTaskAsync。

其中,选项 #2 是更好的做法。

请参阅此封闭式 "off topic" 问题的已接受答案,了解正确使用这两个选项的示例(尽管数字已从我的列表中交换)how to use async and await on a method that is time comsuming