Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

async-await

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;
}
like image 983
Kirsten Avatar asked Aug 03 '18 01:08

Kirsten


People also ask

How do you call async method in MVC action?

STEP 01 Create new MVC Application project, named as "Async". In the File menu, click New Project. In the "New Project" dialog box, under Project types, expand Visual C#, and then click "Web". In the Name box, type "Async", then click on Ok.

What happens when you call an async method?

The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't expected.


1 Answers

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();
}
like image 89
João Fernandes Avatar answered Sep 28 '22 04:09

João Fernandes