Synchronize Progressbar with Execution of class methods

Asked

Viewed 489 times

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 whenever he enters a method he generates an event saying that he entered that method, so I will update a field with the status of the task, that is, when he enters the Listfiles I update the textbox to "Listing Files", for example. And when I exit the method I need another event warning that it has left the method. How can I create these events ?

1 answer

1

The simplest way to do this would be by using BackgroundWorker

Based on your example set up a scenario where will be read the names of the files of a directory, adding each of these files in a list, and for each file read will be updated in a Textbox the percentage of read files, can be updated a ProgressBar in place 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 be done would be to create a class that extends EventArgsand create a EventHandler, but there would have to be other treatments to be able to update the UI.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.