The right and most effective way to verify this is through Tasks
.
1. Turn your method into a task
Let’s turn your method into one Task
so that it is possible to use the Directive await
, if you want to wait for your method to execute to proceed.
private async Task EvokeMetodo(string contrato, int item, bool editar)
{
//retorna um datatable contendo o iten que foi salvo ou editado
DataTable Ret_Contrato = await Ret_Datatable(contrato, item);
int verificador = 0;
//insert
if (!editar)
{
//retorna o numero de linhas afetadas, ou seja, o numero de insert feitos
verificador = await Insert_ContratoItens(Ret_Contrato);
if(verificador > 0)
{
atualiza_ContratoWeb(contrato, item);
}
}
else//update
{
verificador = await Update_ContratoItens(Ret_Contrato);
if (verificador > 0)
{
atualiza_ContratoWeb(contrato, item);
}
}
}
Cannot be used await
in void
, so we created a Task
. Note that this Task
it’s not returning anything, it’s like a void
roughly speaking, as it will only perform. If you want the method to return something, just change Task
for Task<int>
and she’ll need you to return a int
, for example.
2. Execute your Task
Here we will execute your Task
(method) and store the execution in a variable Task
, so you can check your status later. In this example, I put your method execution in an event Click
a button. Note that the Click
button has the directive async
.
private async void button1_Click(object sender, EventArgs e)
{
Task task = Task.Run(async () =>
{
await EvokeMetodo();
});
}
How I used await within the Task.Run
to wait for the execution of the method EvokeMetodo
, it is necessary to use a lambda expression with the directive async()
to "invoke" your method and inform Task.Run
that you want to wait for the execution of the method that it will execute. More specifically in this part:
Task.Run(async () =>
{
await EvokeMetodo();
});
3. Verifying the status of your Task
If noticed earlier, we store the execution (return) of the method Task.Run
in a variable of type Task
calling for task. Through this, it is possible to check the status of the Task
.
if(task.IsCompleted)
{
// Faça alguma coisa
}
Besides task.IsCompleted
we also have task.IsCanceled
and task.IsFaulted
.
It has how to put this chunk of async code that you are running?
– PauloHDSousa
@Paulohdsousa I put an excerpt from one of the methods
Async
, however, we have several methodsAsync
which are executed on different screens at different times..– Thomas Erich Pimentel
Take a look at the answer
– PauloHDSousa