How to use BackGroundWorker in C #

1

I have a query. I would like to use the backgroundworker in my application, but I have no idea how to do it. My application takes a long time to perform certain validations, while this is done, it is frozen. The idea I have is to place a CANCEL VALIDATION button. How could I do it ?. This is my code, here the whole process is done.

  void Listar()
    {
        try
        {
            CN_Guias guias = new CN_Guias();
            DateTime Hoy = DateTime.Today;
            string fecha_actual = Hoy.ToString("dd/MM/yyyy");
            string mes, año;
            mes = txt_mes.Text;
            año = txt_anno.Text;
            if (txt_ruta.Text == "")
            {
                MessageBox.Show("Ingresar Ruta por favor.!!!", "Ingresar Datos", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else if (txt_mes.Text == "")
            {
                MessageBox.Show("Ingrese el Mes por favor.!!!", "Ingresar Datos", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else if (txt_anno.Text == "")
            {
                MessageBox.Show("Ingrese el Año por favor.!!!", "Ingresar Datos", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
           DataTable dtImagenes = 
           guias.Listar_Guias_xMes_xAño(Convert.ToInt32(mes), 
           Convert.ToInt32(año));
                int cantidad_imagen_db = dtImagenes.Rows.Count;
                pgb_cargando.Visible = true;
                pgb_cargando.Maximum = cantidad_imagen_db;
                pgb_cargando.Step = 1;
                pgb_cargando.Value = 0;

                //INICIO FOR
                btn_listar.Enabled = false;
                txt_mes.Enabled = false;
                txt_anno.Enabled = false;
                foreach (DataRow row in dtImagenes.Rows)
                {
                    string nom_imagen_db = row["NroGuia"].ToString().TrimEnd(' ');
                    string[] archivos = Directory.GetFiles(txt_ruta.Text, nom_imagen_db + ".*");
                    string[] archivos2 = Directory.GetFiles(txt_ruta.Text, nom_imagen_db + "_*");
                    if (pgb_cargando.Value <= cantidad_imagen_db)
                    {
                        pgb_cargando.PerformStep();
                    }
                     if (archivos.Length == 0 && archivos2.Length==0) {
                         string f_guia = row["FechaGuia"].ToString();
                         guias.InsertarGuiasValidadas(nom_imagen_db,
                                                         Convert.ToDateTime(f_guia),
                                                         DateTime.Now, "NO"); 
                    }
                    }
                MessageBox.Show("Se realizo la validación correctamente");
                btn_listar.Enabled = true;
                txt_mes.Enabled = true;
                txt_anno.Enabled = true;
                Limpiar();
                //FIN FOR
                //btn_validar.Enabled = true;
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message.ToString());
        }
    }

I hope, you can help me. Thanks.

    
asked by Gonzalo Rios 24.11.2018 в 15:53
source

1 answer

2

The BackgroundWorker class allows you to execute an operation on a separate dedicated subproceso . Time-consuming operations such as downloads and database transactions can cause the (UI) user interface to appear as if it has stopped responding while they are running. If you want a dynamic IU and you are experiencing large delays associated with these operations, the BackgroundWorker class provides an appropriate solution.

To execute a slow operation in the background, you create a BackgroundWorker and hear the events that notify the progress of the operation and a signal when the operation ends. You can programmatically create the BackgroundWorker or drag it to the form from the tab components of the toolbox. If you create the BackgroundWorker in the% Designer Windows Forms , it will appear in the Component Tray and its properties will be displayed in the Properties window.

To set up a background operation, add an event handler for the DoWork event. Call the operation that requires a lot of time in this event handler. To start the operation, call RunWorkerAsync . To receive notifications of progress updates, control the ProgressChanged event. To receive a notification when the operation is complete, control the RunWorkerCompleted event.

You must place what you are going to do within the function DoWork and start BackgroundWorker to work asynchronously backgroundWorker1.RunWorkerAsync(); :

private DataTable dtImagenes = new DataTable();
private string ruta;

void Listar()
{
    try
    {
        CN_Guias guias = new CN_Guias();
        DateTime Hoy = DateTime.Today;
        string fecha_actual = Hoy.ToString("dd/MM/yyyy");
        string mes, año;
        mes = txt_mes.Text;
        año = txt_anno.Text;
        ruta = txt_ruta.Text;
        if (txt_ruta.Text == "")
        {
            MessageBox.Show("Ingresar Ruta por favor.!!!", "Ingresar Datos", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
        else if (txt_mes.Text == "")
        {
            MessageBox.Show("Ingrese el Mes por favor.!!!", "Ingresar Datos", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
        else if (txt_anno.Text == "")
        {
            MessageBox.Show("Ingrese el Año por favor.!!!", "Ingresar Datos", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
        else
        {
            dtImagenes =
            guias.Listar_Guias_xMes_xAño(Convert.ToInt32(mes),
            Convert.ToInt32(año));
            pgb_cargando.Visible = true;
            pgb_cargando.Maximum = dtImagenes.Rows.Count;
            pgb_cargando.Step = 1;
            pgb_cargando.Value = 0;
            btn_listar.Enabled = false;
            txt_mes.Enabled = false;
            txt_anno.Enabled = false;
            if(!backgroundWorker1.IsBusy)
                backgroundWorker1.RunWorkerAsync();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message.ToString());
    }
}

private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    try
    {
        //INICIO FOR
        int i = 0;
        foreach (DataRow row in dtImagenes.Rows)
        {
            if (!backgroundWorker1.CancellationPending)
            {
                string nom_imagen_db = row["NroGuia"].ToString().TrimEnd(' ');
                string[] archivos = Directory.GetFiles(ruta, nom_imagen_db + ".*");
                string[] archivos2 = Directory.GetFiles(ruta, nom_imagen_db + "_*");
                if (archivos.Length == 0 && archivos2.Length == 0)
                {
                    string f_guia = row["FechaGuia"].ToString();
                    guias.InsertarGuiasValidadas(nom_imagen_db,
                                                Convert.ToDateTime(f_guia),
                                                DateTime.Now, "NO");
                }
                backgroundWorker1.ReportProgress(i++);
            }
            else
            {
                e.Cancel = true;
                return;
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message.ToString());
    }
}

private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
    //REPORTAR PROGRESO
    pgb_cargando.Value = e.ProgressPercentage;
}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if (e.Cancelled)
        MessageBox.Show("Se ha cancelado el proceso.");
    else if (e.Error != null)
        MessageBox.Show("Error");
    else
        MessageBox.Show("Se realizo la validación correctamente");
    Habilitar();
    Limpiar();
    //FIN FOR
}

private void Habilitar()
{
    btn_listar.Enabled = true;
    txt_mes.Enabled = true;
    txt_anno.Enabled = true;
}

I'll leave the source if you want more information .

    
answered by 24.11.2018 / 16:16
source