If you want the progress bar to match the progress of your method, then you'll need to update your method to report its progress. Use the
IProgress<T>
interface and the
Progress<T>
class to manage the communication.
IProgress<T> Interface (System) | Microsoft Docs[
^]
Progress<T> Class (System) | Microsoft Docs[
^]
If you want your UI to update whilst the method is running, you'll need to run it on a background thread. Eg:
public void ButtonSubmit_Click(object sender, EventArgs e)
{
SubmitAsync();
}
private async Task SubmitAsync()
{
if (isProcessRunning)
{
MessageBox.Show("A Process is aleady running");
return;
}
var progress = new Progress<int>(n =>
{
progressBar1.Value = n;
label3.Text = ("Progress: " + n+ "%");
});
string outputFile = TextOutputFile.Text;
isProcessRunning = true;
await Task.Run(() =>
{
excelHelper.InsertNewRows(progress);
string fileName = Path.Combine(outputFile, DateTime.Now.ToString("yyyy_MM_dd_") + "SA_Analysis_Report.xlsx");
excelHelper.Save(fileName);
});
MessageBox.Show("File has been added to file");
progressBar1.Value = 0;
isProcessRunning = false;
}
NB: The callback passed to the
Progress<T>
class is automatically invoked through the
SynchronizationContext
captured when the instance is constructed. You don't need to worry about using
Invoke
to update the UI in the callback.