Synchronize ProgressBar with Execution of methods of a class

0

In my project I have a class that has three methods:

static List<string> ListaArquivos(string path){...}
static void CriaArquivoUnico(List<string> listaArquivos){...}
static void AbreArquivoUnico(string pathArquivoUnico){...}

What I am trying to do is that every time it gets into a method it generates an event saying that it has entered that method, so I will update a field with the status of the task, that is, when I enter the Filelist I update the textbox for "Listing Files", for example. And when I quit the method I need another event warning that it has dropped the method. How can I create these events?

    
asked by anonymous 15.09.2015 / 19:42

1 answer

1

The simplest way to do this would be to use BackgroundWorker

Based on your example, I set up a scenario where the file names of a directory will be read by adding each of those files in a list, and for each file read the percentage of read files will be updated in a TextBox, ProgressBar instead of TextBox .

    List<string> ListaArquivos(string path)
    {
        List<string> listArquivos = new List<string>();

        BackgroundWorker workerLeituraArquivos = new BackgroundWorker();
        workerLeituraArquivos.WorkerReportsProgress = true;
        workerLeituraArquivos.DoWork += (sender, e) =>
        {
            var arrayArquivos = Directory.GetFiles(path);
            for (int i = 0; i < arrayArquivos.Length; i++)
            {
                listArquivos.Add(arrayArquivos[i]);

                // calculo da porcentagem concluida
                var porcentagem = (100 / arrayArquivos.Length) * (i + 1);
                workerLeituraArquivos.ReportProgress(porcentagem);

                // adicionado apenas para dar tempo de notar a alteração do textbox
                Thread.Sleep(1000); 
            }
        };

        workerLeituraArquivos.ProgressChanged += (sender, e) =>
        {
            txtStatus.Text = string.Format("Listando arquivos. {0}% concluído", e.ProgressPercentage);
        };

        workerLeituraArquivos.RunWorkerCompleted += (sender, e) =>
        {
            txtStatus.Text = "Listagem de arquivos concluída";
        };

        workerLeituraArquivos.RunWorkerAsync();

        return listArquivos;
    }

Another way to do this would be to create a class that would stretch EventArgs and create a EventHandler , but then other treatments would have to be done to be able to update the UI.

    
06.09.2016 / 21:05