小编use*_*038的帖子

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根本不会冻结!

c# asynchronous async-await

0
推荐指数
1
解决办法
145
查看次数

标签 统计

async-await ×1

asynchronous ×1

c# ×1