I got a WPF window and i want to do some work in a background thread..
when the work is done i want to do it again.. like a loop with a UI update between
my code:
private void InitializeBackgroundWorker() { m_stopCamera = false; m_worker = new BackgroundWorker(); m_worker.DoWork += new DoWorkEventHandler(worker_DoWork); m_worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted); m_worker.WorkerSupportsCancellation = true; } unsafe void worker_DoWork(object sender, DoWorkEventArgs e) { // my work.... e.Result = new MyResultClass(p1,p2..); } private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (e.Cancelled) return; if (e.Error != null) { Logger.LogException(e.Error.ToString()); Window_Closed(this, new EventArgs()); } try { //UI work.. DetectionResult result = e.Result as DetectionResult; if (result.Cancel == true) { m_DetectedObjID = result.DetectionID; // PlaySound(); audio_MediaEnded(this, new EventArgs()); } else ((BackgroundWorker)sender).RunWorkerAsync(); } catch (Exception ex) { Logger.LogException(ex.ToString()); Window_Closed(this,new EventArgs()); } } I know this code isn't good cause i got a threading hell and can't debug it properly
for example.. when the code is running and i click the close button i can see in the event the the worker is busy all the time.. resulting an infinity loop..
private void Window_Closed(object sender, EventArgs e) { if (m_worker.IsBusy) m_worker.CancelAsync(); while(m_worker.IsBusy); base.Close(); } } What am i doing wrong ? Thanks
worker_DoWorkmethod?e.Cancelledtotrueby yourself.