How to show an image before ending an event? - C #

1

I'm trying to make 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 is not 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 to 6 seconds to respond in the function ConectarVaseDatos() but the gif is not visible until the event ends.

Could someone tell me how could I do this?

    
asked by Jesse R. Jose 22.07.2017 в 17:22
source

2 answers

2

Unless you're using an older version of .NET (before .NET 4.5), I recommend using Task using the syntax async/await . This allows the flow of the code to maintain its clarity, but achieves the goal. Note how minimal the changes are compared to your original code:

private async void btnIniciarSesion_Click(object sender, EventArgs e)
{
    loading.Visible = true;
    if (await Task.Run(() => ConectarBaseDatos()))
    {
        OpenFormulario();
        this.Close();
    }
    else MessageBox.Show("Usuario o contraseña, incorrectos");
    loading.Visible = false;
}

The changes are only two:

  • Add the keyword async in the signature of the btnIniciarSesion_Click method.
  • Replace ConectarBaseDatos() with await Task.Run(() => ConectarBaseDatos())
  • answered by 21.11.2017 / 16:50
    source
    0

    I found a way to do it.

    private void btnIniciarSesion_Click(object sender, EventArgs e)
    {
       loading.Visible = true;
       Task.Run<bool>(() =>
            {
                return ConnectDataBase();
            })
            .ContinueWith(t =>
            {
                if (t.Result)
                {                   
    
                    if (message == "")
                    {
                        lblBienvenido.Text = "Bienvenido\n" + Usuario.Nombre + " " + Usuario.Apellido;
                        ptbLoadin.Visible = !(lblBienvenido.Visible = true);
                        this.Refresh();
                        System.Threading.Thread.Sleep(4000);
                        MDIPrincipal mdip = new MDIPrincipal();
                        this.Hide();
                        mdip.Text += " - ( " + Usuario.Tipo + " )";
                        mdip.Show();
                    }
                    else if (Usuario.Tipo != "Admin") FrmLogin_Load(null, null);
                    else this.Close();
    
                }
                else resetForm();
            }, TaskScheduler.FromCurrentSynchronizationContext());
    }
    
        
    answered by 21.11.2017 в 16:47