async/await无法正常工作

use*_*038 0 c# asynchronous async-await

我的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;
}
Run Code Online (Sandbox Code Playgroud)

我不知道我做错了什么.我知道我是新手,这就是我在这里学习的原因(也就是不要判断!).

PS当我试图改变时

using (StreamReader sr = new StreamReader(File.OpenRead(s)))
{
    textToReturn = sr.ReadToEnd();
}
Run Code Online (Sandbox Code Playgroud)

用简单的Thread.Sleep(2500)方法.GUI根本不会冻结!

Nko*_*osi 6

async void除了异步事件处理程序之外,避免使用,ReadToEndAsync并且可以一直使用并使代码异步.

private async Task SetUpTextBox(string s) {
    //This method is called in button event
    string textToSet = await GetTextAsync(s);
    read_Box.Text = textToSet;
}

private async Task<string> GetTextAsync(string s) {
    string textToReturn = "Hello";
    using (StreamReader sr = new StreamReader(File.OpenRead(s))) {
        textToReturn = await sr.ReadToEndAsync();
    }
    return textToReturn;
}
Run Code Online (Sandbox Code Playgroud)

SetUpTextBox在按钮单击事件处理程序中调用的示例,如原始帖子的注释所暗示的

public async void OnBtnClicked(object sender, EventArgs args) {
    try {
        //...

        await SetUpTextBox("some path");

        //..
    } catch {
        //... handle error
    }
}
Run Code Online (Sandbox Code Playgroud)

您还应该try/catch使用async void事件处理程序放置所有内容,否则将无法观察到任何异常.

参考Async/Await - 异步编程的最佳实践