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 EventArgs
and create a EventHandler
, but there would have to be other treatments to be able to update the UI.