I am using a BackgroundWorker
to perform some processing jobs, while showing a progress basr on the foreground. Now I know that I am not supposed to access properties that are used by other threads, as this seems to cause all sorts of errors. But in the following example, I don't think I am doing anything such, yet the BackgroundWorker
magically terminates when it reaches the ShowDialog()
method:
public class ProcessingWindow
{
List<ProcessingJob> m_processingJobs = new List<ProcessingJob>();
private BackgroundWorker m_backGroundWorker = new BackgroundWorker();
public ProcessingWindow()
{
InitializeComponent();
/* Fill m_processingJobs with jobs */
m_backGroundWorker.WorkerReportsProgress = true;
m_backGroundWorker.WorkerSupportsCancellation = true;
m_backGroundWorker.DoWork += m_backgroundWorker_DoWork;
m_backGroundWorker.ProgressChanged += m_backgroundWorker_ProgressChanged;
m_backGroundWorker.RunWorkerCompleted += m_backgroundWorker_RunWorkerCompleted;
this.Loaded += ProcessingProgressWindow_Loaded;
}
void ProcessingWindow_Loaded(object sender, RoutedEventArgs e)
{
m_backGroundWorker.RunWorkerAsync();
}
private void m_backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
foreach (ProcessingJob job in m_processingJobs )
{
if (job.somethingIsWrong)
{
SomethingIsWrongDialog dialog = new SomethingIsWrongDialog(); // <-- Here it crashes!
// This statement is therefore never reached:
dialog.showDialog();
}
}
}
private void m_backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Debug.WriteLine("Finished!");
this.Close();
}
}
So my program will hit the constructor of SomethingIsWrongDialog
, and then, instead of crashing, just stop the thread, and perform the m_backgroundWorker_RunWorkerCompleted
method as if nothing happened. Why is this wrong?