c# - 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!
解决方案
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
推荐阅读
- flask - 如何将随机颜色十六进制从烧瓶后端发送到 html
- javascript - jQuery 替代 div 元素
- android-room - Room.databaseBuilder 中的数据库名称是什么?
- homebrew - HomeBrew 无法安装任何东西
- c# - NotifyIcon 停留的时间比我输入的时间长
- javascript - Laravel ajax - 此路由不支持 POST 方法。支持的方法:GET、HEAD
- git - 有没有一种方法可以轻松地将主分支合并到 GIT 中的功能分支,然后反其道而行之?
- java - 如何获取针对网页中特定标签的所有值
- redis - ServiceStack Messaging API:可以广播吗?
- python - Python Selenium Chrome 驱动程序 - nseindia - 得到 403