3

I have trying to update some data without asking users on windows application, but when I try to download , app isn't usable and controls aren't touchable.

Code:

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

res = client.DownloadString(url);
}
4

1 回答 1

1

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

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

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

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

有关正确使用这两个选项的示例(尽管数字已从我的列表中交换),请参阅这个已关闭的“离题”问题的已接受答案,如何在耗时的方法上使用 async 和 await

于 2017-08-04T14:01:18.483 回答