Resolved Async and Await in C# Winform

Anonymous

Well-known member
Joined
Sep 29, 2020
Messages
94
Programming Experience
Beginner
I am working on a winform Application that processes a very large excel file. During the execution it was freezing the UI. So, I found out about async and await in C# that can keep the UI responsive when performing long task. I have implemented them the following way -


C#:
private async void btnClick()
{
    PleaseWait pleasewait = new PleaseWait();
    pleasewait.Show();

    // Perform your long-running task asynchronously
    await Task.Run(() => ProcessExcel());

    pleasewait.Close();
    MessageBox.Show("Processing Complete!")
}



private void ProcessExcel()
{
 //read excel file
//does some calculations on the rows
// write output in another excel file
}


This is working and my UI is also responsive. But I wanted to ask should I make ProcessExcel() also async?

Another thing that I have noticed. That when I am in the debugging using breakpoints, my UI is unresponsive. I wanted to find out what happens if someones accidentally closes the please wait form.
Though, I have figured out that nothing happens and the main form continues it execution as it.

My apologies for the basic questions, I have just discovered await and async.
 
Last edited:
As you've written it, there's actually no point. As you have control of the code, it would be more proper to declare ProcessExcel async and not use Task.Run:
C#:
private async Task ProcessExcelAsync()
and:
C#:
await ProcessExcelAsync();
Note that a synchronous void method becomes async Task. The exception to that rule is event handlers, which must be declared void.
 
As a side note: simply redeclaring void ProcessExcel() as async Task ProcessExcelAsync() and just calling await ProcessExcelAsync() directlywithout changing the code within the method is going to get the OP back to his old freezing UI again.

The reason why the OP's code unfroze was because the Task.Run() starts another thread and returns a Task object. All the work is done in that other thread. The await yields the current thread, and will wait for the object to signal to be done to be done executing.

On the other hand, calling await ProcessExcelAsync() will not yield until it gets a Task back. But if the method body remains unchanged, then method will still run synchronously on the UI thread. Extra work will need to be done in the method body to make it truly asynchronous.
 
Back
Top Bottom