0

Estou desenvolvendo uma aplicação onde me deparei com um erro que andei consultando, mas não consegui entender exatamente a forma de corrigir. Resumindo:

Criei um formulário que abre como Dialog e me dá a opção de selecionar um arquivo .xlsx. Ele importa todos os valores da planilha e enquanto lê os valores adiciona ao banco Mysql.

Adicionei a classe BackgroundWork para efetuar o processo de contagem da operação e retornar em um progressBar. Porem toda vez que executa um insert na tabela quando vai fazer a leitura da posição atual que está para passar o progresso, retorna a seguinte mensagem; inserir a descrição da imagem aqui

Gostaria de uma ajuda para entender onde estou errando. Segue código abaixo.

public partial class ImportCFOPForm : Form
    {
        private FormServices FormServices { get; set; }
        private BackgroundWorker Worker { get; set; }
        private CFOPController Controller { get; set; }
        private CFOPForm CFOPForm { get; set; }
        private FormLoad FormLoad { get; set; }
        private int InitParmForm { get; set; }
        public string filePath { get; set; }

    public ImportCFOPForm(CFOPController _controller, Form _form)
    {
        InitializeComponent();
        SetController(_controller);
        SetCFOPForm((CFOPForm)_form);
        FormLoad = new FormLoad();
        InitValuesForm();
        RunDialog();
    }

    private void WorkerProgress_DoWork(object sender, DoWorkEventArgs e)
    {
        LoadSpreadsheetAsync();
    }

    private void WorkerProgress_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        ProgressBarDefault.Value = e.ProgressPercentage;
        LblValuePorcent.Text = $"{ProgressBarDefault.Value}%";
    }

    private void WorkerProgress_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        //display("");
    }

    private void ImportCFOPForm_MouseDown(object sender, MouseEventArgs e)
    {
        FormServices.MoveForm(this);
    }

    private void BtnOk_Click(object sender, System.EventArgs e)
    {
        if (InitParmForm.Equals(1))
        {
            LblIsValid.Visible = false;
            LblProgress.Visible = true;
            LblValuePorcent.Visible = true;
            ProgressBarDefault.Visible = true;
            BtnOk.Visible = false;
            WorkerProgress.RunWorkerAsync();
        }
        else
        {
            this.DialogResult = DialogResult.OK;
        }

    }

    private async void LoadSpreadsheetAsync() 
    {
        IExcelDataReader excelReader;
        FileStream stream = File.Open(this.filePath, FileMode.Open, FileAccess.Read);
        string[] returnPosition = new string[2];

        if (Path.GetExtension(this.filePath).ToUpper().Equals(ConstantValues.TYPE_XLS))
        {
            excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
        }
        else
        {
            excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
        }

        var conf = new ExcelDataSetConfiguration
        {
            ConfigureDataTable = _ => new ExcelDataTableConfiguration
            {
                UseHeaderRow = true
            }
        };

        DataSet result = excelReader.AsDataSet(conf);
        var dataTable = result.Tables[0];

        //excelReader.Close();

        if (dataTable.Rows.Count > 0)
        {

            int totalProgress = dataTable.Rows.Count;

            try
            {
                for (var i = 0; i < totalProgress; i++)
                { 
                    WorkerProgress.ReportProgress((int)(i + 1 * 100 / totalProgress));

                    string input = dataTable.Rows[i][0].ToString().Trim();

                    if (!string.IsNullOrEmpty(input))
                    {
                        char[] charsToTrim = { '*', '.' };
                        input = input.TrimStart(charsToTrim);

                        int finalString = input.Length;
                        string cfopValue = $"{input.Substring(0, 1)}.{input.Substring(1, finalString - 1)}";
                        string description = dataTable.Rows[i][1].ToString();
                        string application = dataTable.Rows[i][2].ToString();

                        var db = new CFOPDB()
                        {
                            CFOPValue = cfopValue,
                            Description = description,
                            Application = application
                        };

                        if (!db.CFOPValue.Equals(string.Empty))
                        {
                            returnPosition = await Controller.Insert(db);

                            if (returnPosition[0].Equals(ReturnMsgVersionEnum.sucess.ToString())) 
                            {
                                Controller = SessionStorage.NewCFOPController();
                            }

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                FormLoad.DialogSimpleMsg(
                            CFOPForm,
                            string.IsNullOrEmpty(ex.InnerException.Message)
                            ? ex.Message
                            : ex.InnerException.Message,
                            TypeMsgReturnEnum.ERRO.ToString(),
                            MessageBoxIcon.Error);
            }

            if (returnPosition[0].Equals(ReturnMsgVersionEnum.sucess.ToString()))
            {
                
                FormLoad.DialogSimpleMsg(
                            CFOPForm,
                            $"A planilha {stream.Name}, foi importada com sucesso.",
                            TypeMsgReturnEnum.SUCESSO.ToString(),
                            MessageBoxIcon.Information);
            }
            else
            {
                FormLoad.DialogSimpleMsg(
                                CFOPForm,
                                returnPosition[1],
                                TypeMsgReturnEnum.ERRO.ToString(),
                                MessageBoxIcon.Error);
            }
        }
    }

    private void InitValuesForm()
    {
        WorkerProgress.WorkerSupportsCancellation = true;
        WorkerProgress.WorkerReportsProgress = true;
        FormServices = new FormServices();
        InitParmForm = 1;
        LblIsValid.Visible = true;
        LblProgress.Visible = false;
        LblValuePorcent.Visible = false;
        ProgressBarDefault.Visible = false;
        BtnOk.Visible = true;
    }

    private void RunDialog()
    {
        OpenFileDialog openDialog = new OpenFileDialog();
        //openDialog.Filter = "*.xlsx";

        openDialog.Title = "Selecione o Arquivo";

        if (openDialog.ShowDialog() == DialogResult.OK)
        {
            this.filePath = openDialog.FileName;
        }
    }

    private void SetController(CFOPController _controller)
    {
        this.Controller = _controller;
    }
    
    private void SetCFOPForm(CFOPForm _cfopForm)
    {
        this.CFOPForm = _cfopForm;
    }

1 Resposta 1

0

O Problema é que você está chamando um método assíncrono dentro do backgroundWorker. Quando ele é chamado, o backgroundWorker finalizar sua execução, e dentro de LoadSpreadsheetAsync você chama o ReporProgress (mas o backgroundWorker já finalizou sua execução...)

o que acontece de fato é que você inicia uma nova thread no backgroundWorker, e chama um método assíncrono iniciando outra thread novamente.

retire a opção de async do LoadSpreadsheetAsync que deve resolver esse problema

1
  • Boa tarde Rovann Linhalis. Nosso perfeito, obrigado pela dica, editei o método insert como síncrono e corrigi o método LoadSpreadsheet e resolveu o problema. Muito obrigado pelo auxilio. 6/07/2020 às 19:39

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .