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.