ProgressBar and BackgroundWorker in C #

4

I'm creating an application with Firebird 2.5 in which I need it to read a .sql file with instructions to populate the database if these processes have not yet been done, because it is a bit long and because I do not know I want to add "não respondendo" to ProgressBar , but when I add them I'm now getting the following error while executing the commands: BackgroundWorker . Now if I run the application without using Connection must be valid and open and ProgressBar this error does not occur. This is the code I'm working on and the image on the screen is working, and it comes to an end without making a mistake. I've relied on this example of DevMedia: link

using System;
using System.Data;
using System.Windows.Forms;
using Engebuilder.Library;
using Engebuilder.UI.Windows.General;
using Engebuilder.UI;
using Engebuilder.Data;
using System.Reflection;
using System.Drawing;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using System.Text;

namespace GSD
{
    public partial class FomAux : Engebuilder.UI.Windows.General.DefaultForm
    {
        System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();

        public FomAux()
        {
            this.InitializeComponent();
            this.SetComponents(components);
        }

        private void FomAux_Load(object sender, System.EventArgs e)
        {
            timer.Interval = 10;
            timer.Enabled = true;
            timer.Tick += new EventHandler(Timer_Tick);
        }

        int contador = 0;

        private void Timer_Tick(object sender, System.EventArgs e)
        {
            try
            {
                contador += 1;

                if (contador >= 5)
                {
                    timer.Enabled = false;
                    contador = 0;

                    backgroundWorkerPopularBanco.RunWorkerAsync();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ocorreu um erro inesperado: \"" + ex.Message + "\"", "Atenção!", MessageBoxButtons.OK, MessageBoxIcon.Information);

                this.Close();
            }
        }


        private void backgroundWorkerPopularBanco_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            try
            {
                string diretorio = Directory.GetCurrentDirectory();
                string filePath = Path.Combine(diretorio, "SCRIPT.sql");

                if (File.Exists(filePath))
                {
                    string populouBanco = Engebuilder.Library.LDataAccess.GetDataToString("SELECT CONFIG_SISTEMA.CONF_SIS_POPULOUBANCO FROM CONFIG_SISTEMA");

                    if (populouBanco.Trim().Equals("") || populouBanco.Trim().Equals("N"))
                    {
                        StreamReader leitor = new StreamReader(filePath, Encoding.UTF7);
                        string comteudoArq = leitor.ReadToEnd();

                        string[] comando = comteudoArq.Trim().Split(new Char[] { '!' });

                        Int64 contador = 0;

                        foreach (string valor in comando)
                        {
                            contador++;

                            if (!valor.Trim().Equals(""))
                            {
                                Engebuilder.Library.LDataAccess.ExecuteCommand(valor.Trim());

                                //faz a thread dormir por "p" milissegundos a cada passagem do loop
                                //Thread.Sleep(p);

                                listBox.BeginInvoke(
                                    new Action(() =>
                                    {
                                        listBox.Items.Add("[ " + DateTime.Now.ToString() + " ] - Processo: " + contador.ToString() + " comcluído.");
                                        listBox.SelectedIndex = listBox.Items.Count - 1;
                                    }
                                ));
                            }
                        }

                        string sqlConfig = "INSERT INTO CONFIG_SISTEMA (CONF_SIS_POPULOUBANCO, CONF_SIS_DATA, CONFI_SIS_LOG) "
                        + " VALUES('S', '" + DateTime.Now.ToString().Replace("/", ".") + "', NULL)";
                        Engebuilder.Library.LDataAccess.ExecuteCommand(sqlConfig.Trim());

                        DialogResult result = MessageBox.Show("Configurações Concluídas com Sucesso!", "Atenção!", MessageBoxButtons.OK, MessageBoxIcon.Information);

                        if (result.Equals(DialogResult.OK))
                            this.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ocoreu um erro Realizar algumas Configurações: \"" + ex.Message + "\"", "Atenção!", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void backgroundWorkerPopularBanco_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            //Caso cancelado...
            if (e.Cancelled)
            {
                // reconfigura a progressbar para o padrao.
                ProgressBarPopularBanco.MarqueeAnimationSpeed = 0;
                ProgressBarPopularBanco.Style = ProgressBarStyle.Blocks;
                ProgressBarPopularBanco.Value = 0;

                //caso a operação seja cancelada, informa ao usuario.
                listBox.Items.Add("[ " + DateTime.Now.ToString() + " ] - Operação Cancelada pelo Usuário!");

                //limpa a label
                label1.Text = string.Empty;
            }
            else if (e.Error != null)
            {
                //informa ao usuario do acontecimento de algum erro.
                listBox.Items.Add("[ " + DateTime.Now.ToString() + " ] - Aconteceu um erro durante a execução do processo!");
                // reconfigura a progressbar para o padrao.
                ProgressBarPopularBanco.MarqueeAnimationSpeed = 0;
                ProgressBarPopularBanco.Style = ProgressBarStyle.Blocks;
                ProgressBarPopularBanco.Value = 0;
            }
            else
            {
                //informa que a tarefa foi concluida com sucesso.
                listBox.Items.Add("[ " + DateTime.Now.ToString() + " ] - Processos Concluidos com Sucesso!");
                //Carrega todo progressbar.
                ProgressBarPopularBanco.MarqueeAnimationSpeed = 0;
                ProgressBarPopularBanco.Style = ProgressBarStyle.Blocks;
                ProgressBarPopularBanco.Value = 100;
                label1.Text = ProgressBarPopularBanco.Value.ToString() + "%";
            }
        }
    }
}

    
asked by anonymous 14.01.2016 / 21:45

1 answer

1

Dear Joachim,

Among many causes for this problem, I suppose this is a winforms application, correct? Typically these problems are related to thread execution (the backgroundworker is one of them ...). Note that winforms applications are in thread-safe , that is, running a routine should ONLY start if another routine is terminated. When trying to execute routines in parallel bizarre messages usually happen, (when they did not happen before attempting to use parallel runs). Well, it is still possible to run parallel routines through the use of TASK (a thread with an abstraction level better than the threads of previous versions of .NET) So, they follow paths to better elucidate your problem

  • Study on [Task parallel]
  • Thread safe calls to winforms
  • Possibly try to change the block where you see string sqlConfig="...." into this.Invoke(new MethodInvoker(() =>{ sqlConfig="...." Engebuilder.Library.LDataAccess.ExecuteCommand(sqlConfig.Trim()); };
  • Tip: Prefer XML than TXT file. (I went through a lot of problems with it ...) In addition, .NET has a wide range of methods for manipulating these files.
  • See this code to better understand:

    #region Thread Status da Conexao
    /// <summary>
    /// Lanca thread para verificação de conexao com banco de dados a cada 5s
    /// <para>Notifica caso conexão caia</para>
    /// </summary>
    private void ThreadConexao()
    {
        Task conexao = new Task(() =>
           {
               bool isconetado = true;
               try
               {
                   while (true)
                   {
                       //Verifica conexao com o banco de dados
                       isconetado = Connect();
                       //Todas as vezes que a rotina é executada
                       //o metodo MethoInvoker é acionado e direciona a chamada ao controle do formulario                           
                       if (isconetado)
                       {
                           this.Invoke(new MethodInvoker(() =>
                           {
                               //Exibir no rodape do form a informacao de conectado
                               label1.Text = "Conectado";
                              //Uma imagem contendo um simbolo de conectado
                               pictureBox1.Image = Properties.Resources.connect_style2;
                           }));
    
                       }
                       else
                       {
                           this.Invoke(new MethodInvoker(() =>
                           {
                               //Exibir no rodape do form a informacao de desconectado
                               label1.Text = "Desconectado";
                               //Uma imagem contendo um simbolo de desconectado
                               pictureBox1.Image = Properties.Resources.disconnect_style2;
    
                           }));
    
                       }
                       //A cada 5 segundos volta a fazer a verificação de conexao com o banco de dados
                       Thread.Sleep(5000);
                   }
    
               }
               catch (Exception) { }
    
    
           });
    
        conexao.Start();
    }
    
    
    
    #endregion
    
  • A sample image

        
    05.10.2016 / 15:57