I've read about Invoke(ing) controls and whatnot... I don't know WHAT controls I'm supposed to invoke as both my main form and dialog form have more than one, hence my question here. I've read this and this and this ... I simply don't understand how to apply it to my situation. Is there a tutorial somewhere that I go read to try to understand better?
I have a winform app (C#) that does some work. Some of this work may take a while so I thought I'd provide a progress dialog of sorts to alert the user that activity is taking place (and not simply relying on a list control flashing periodically to indicate something updated).
So, I added a new form to my project, added a few items of interest (# of items to process, estimated completion time, current item and an overall progress bar).
public ProgressDialog Progress { get; set; }
public Form1()
{
Progress = new ProgressDialog(this);
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true;
}
I set the main work to be done in a backgroundworker once the Process button is clicked.
private void buttonProcess_Click(object sender, EventArgs e)
{
if (backgroundWorker1.IsBusy != true)
{
backgroundWorker1.RunWorkerAsync();
Progress.ShowDialog();
}
}
From a method that is called on that thread, I call a method on my ProgressDialog form:
Progress.UpdateDialog(numFiles: filesToProcess.Count,
processTime: TimeSpan.FromTicks(filesToProcess.Count * TimeSpan.TicksPerSecond * 20)); // 20s is an estimated time, it will be updated after first file is processed.
The code in question there (in ProgressDialog.cs):
public void UpdateDialog(int percentComplete = 0, string fileName = "", int numFiles = 0, TimeSpan? processTime = null)
{
...
if (numFiles > 0)
{
labelNumFiles.Text = Convert.ToString(numFiles);
}
if (!processTime.Equals(null))
{
labelProcessTime.Text = Convert.ToString(processTime);
}
}
Which results in the following error:
An exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll but was not handled in user code
Additional information: Cross-thread operation not valid: Control 'ProgressDialog' accessed from a thread other than the thread it was created on.
Additionally, the main form has two list controls that need to be updated as the files are processed: a processed file list and an error file list. Had things working fine until I got the brilliant idea to add the progress dialog. LOL So, what is the proper way to handle updating a progress dialog?