I am trying to do a loading for a section start form. I have put an animated gif to make the loading effect.
What happens is that when I use the property loading.Visible = true
, it doesn't become visible until the event click
ends.
Here is the code.
private void btnIniciarSesion_Click(object sender, EventArgs e)
{
loading.Visible = true;
if (ConectarBaseDatos())
{
OpenFormulario();
this.Close();
}
else MessageBox.Show("Usuario o contraseña, incorrectos");
loading.Visible = false;
}
The Database takes 3-6 seconds to respond to the function ConectarVaseDatos()
but the gif doesn't become visible until the event is over.
Could someone tell me how I could do this?
Unless you're using an older version of .NET (before .NET 4.5), I recommend using the
Task
using .NET syntaxasync/await
. This allows the code flow to remain clear, but accomplishes the goal. Notice how minimal the changes are compared to your original code:The changes are only two:
async
in the method signaturebtnIniciarSesion_Click
.ConectarBaseDatos()
withawait Task.Run(() => ConectarBaseDatos())
I found a way to do it.