【发布时间】:2018-05-06 17:08:00
【问题描述】:
我的 async/await 方法有问题。我是 async/await 的新手,似乎无法正常工作。
当我有以下情况时,GUI 冻结。
private async void SetUpTextBox(string s)
{
//This method is called in button event
string textToSet = await GetTextA(s);
read_Box.Text = textToSet;
}
private Task<string> GetTextA(string s)
{
return Task.Run(() => GetText(s));
}
private string GetText(string s)
{
string textToReturn = "Hello";
using (StreamReader sr = new StreamReader(File.OpenRead(s)))
{
textToReturn = sr.ReadToEnd();
}
return textToReturn;
}
我不知道我做错了什么。我知道我是新手,这就是我来这里学习的原因(也就是不要评判!)。
P.S 当我试图改变时
using (StreamReader sr = new StreamReader(File.OpenRead(s)))
{
textToReturn = sr.ReadToEnd();
}
使用简单的Thread.Sleep(2500) 方法。 GUI 根本不会冻结!
【问题讨论】:
-
请注意,您的
GetText函数已经存在,它被称为File.ReadAllText。 -
在我没有提到之前我也试过了。它仍然冻结了 GUI。
-
您提到了一个 GUI,但没有告诉我们是哪一个,也没有包括您如何连接到它。写一个正确的minimal reproducible example,包括ButtonClick 等。
-
我有一个关于您为什么阻止 UI 的假设:您尝试放入行中的文本数量
read_Box.Text = textToSet;(在 UI 线程中运行)太多了。编辑:当然,当文本很小时,例如“Hello”,它不会阻塞 UI。 -
@HenkHolterman 对此感到抱歉。只是普通的winforms。
标签: c# asynchronous async-await