How do i call an async method from a winforms button click event?

纵饮孤独 提交于 2021-02-07 14:47:24

问题


I have an I/O bound method that I want to run asynchronously.

In the help docs it mentions that I should use async and await without Task.Run

to quote

For I/O-bound code, you await an operation which returns a Task or Task inside of an async method.

How do I do this from a winforms button click event?

I have tried

private void button_Click(object sender, EventArgs e)
{ 
      await doLoadJob();
}

private async Task<int> doLoadJob()
{
    await loadJob();   
    return 0;
}

回答1:


Your button_Click method needs to be async. Place a async between private and void.

private async void button_Click(object sender, EventArgs e)
{ 
     await LongOperation();
}


来源:https://stackoverflow.com/questions/51664291/how-do-i-call-an-async-method-from-a-winforms-button-click-event

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!