How to show "wait, load data" using asynchronous programming?

Asked

Viewed 1,864 times

2

How can I use asynchronous programming with Async and Await so that it appears in the middle of the grid "Wait for loading data" while searching for data in the database and fill in with Datatable on the Grid?

Programming in Windows Form and C#.

1 answer

2

Not knowing how your code is structured instead of responding using async and await I present a solution using the class Task:

MostraAguarde(true);
var task = Task.Factory.StartNew(() =>
{
    LerDados();
});
task.ContinueWith(
t =>
{
    MostraAguarde(false);
},TaskScheduler.FromCurrentSynchronizationContext());

Create the method MostraAguarde(bool mostrar) to display the message when the parameter passed is true and withdraw the message when false.
Create the method LerDados() where the data will be read.

I think the code is easy to understand:

The message is displayed. One Task is created to execute the method that reads the data.
When the method LerDados() returns, to Task is terminated and the message is withdrawn.

EDIT
Using await would be something like that:

MostraAguarde(true);
try
{
    await LerDados();
}
catch (Exception e)
{
    ProcessErrors(e);            
}
finally
{
    MostraAguarde(false);
}

The method LerDados() will have to return Task or Task<T>:

private Task LerDados()
{
    ....
}
  • In the first example, the continuation will run in another thread, and therefore you will not be able to update the UI. The correct thing would be to wait for the task using await to ensure context "flow" - await Task.Run(LerDados); MostrarAguarde(false);

  • "The Lerdados() method must be declared async" - not necessarily the only requirement is Task or Task<T>.

  • @dcastro You are right, async is only necessary if used await within the method. Regarding the first situation was my distraction. I use this approach in WPF where MostraAguarde is a property that, via Binding, makes Hide/show component.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.