首页 > 解决方案 > async/await does not work properly

问题描述

I have problem with async/await method of mine. I am new into async/await and seems I can't get it to work correctly.

The GUI freezes when I have the following.

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;
}

I don't know what I am doing wrong. I know I am new into this and that's why I am here to learn (a.k.a don't judge!).

P.S When I tried to change

using (StreamReader sr = new StreamReader(File.OpenRead(s)))
{
    textToReturn = sr.ReadToEnd();
}

With simple Thread.Sleep(2500) method. The GUI doesn't freeze at all!

标签: c#asynchronousasync-await

解决方案


Avoid async void except for async event handlers, plus you can use ReadToEndAsync and make code async all the way through.

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;
}

An example of calling SetUpTextBox within the button click event handler, as implied by the comment from original post

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

        await SetUpTextBox("some path");

        //..
    } catch {
        //... handle error
    }
}

You should also put a try/catch around everything with the an async void event handler, otherwise any exceptions will go unobserved.

Reference Async/Await - Best Practices in Asynchronous Programming


推荐阅读