How can I exit (stop) my dispatcher?

I would like to stop the dispatcher that was running in main () when the user clicks a button.

private void button_start_Click(object sender, RoutedEventArgs e) { ... Camera.EventFrame -= onFrameEventFocusCam; //unsubscribe event while (!Dispatcher.HasShutdownStarted) { // test if Dispatcher started shutdown --> ok, it does but never finishs...! } ... } private void onFrameEventFocusCam(object sender, EventArgs e) { ... Dispatcher.Invoke(new Action(() => { // Convert bitmap to WPF-Image var bmp = new Bitmap(bitmap); var hBitmap = bmp.GetHbitmap(); System.Windows.Media.ImageSource wpfBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); image_fokus.Source = wpfBitmap; image_fokus.Stretch = System.Windows.Media.Stretch.UniformToFill; DeleteObject(hBitmap); bitmap.Dispose(); })); GC.Collect(); } 

When I run this code, I get the following error message when it is stopped in onFrameEventFocusCam :

  Error-Message: Thread was interrupted from a waiting state. 
+8
c # wpf dispatcher
source share
3 answers

When you call BeginInvokeDispatcher , this causes the dispatcher to shut down asynchronously; it should still finish processing the current dispatcher frame before it shuts down. But since you are expecting the dispatch to complete in the loop, the current frame never ends, so the dispatcher cannot complete the shutdown. Instead, you can subscribe to the ShutdownFinished event to determine when the dispatcher shuts down.

As for the error you get in onFrameEventFocusCam , I think this is due to the dispatcher being disabled, so it cannot handle Invoke ; from the documentation:

Once the process is completed, all pending work items in the queue are interrupted.

I'm not sure what you are trying to do, but closing the main dispatcher is most likely not a way to do this, as this will effectively stop the application ...

+2
source share

It is not clear what your original intention was.

This code should hang (almost) forever, because HasShutdownStarted does not become true until the application exits.

 while (!Dispatcher.HasShutdownStarted) { // test if Dispatcher started shutdown --> ok, it does but never finishs...! } 

This code provides for delegate execution in the user interface thread. It looks great.

 private void onFrameEventFocusCam(object sender, EventArgs e) { ... Dispatcher.Invoke(new Action(() => { ... } } 

This code seems to be potentially problematic because if DeleteObject actually frees the handle, then the handle can be released twice, once in Delete and once in Dispose. It can quit.

 DeleteObject(hBitmap); bitmap.Dispose(); 
+2
source share

To make the stop manager run in your main application thread, you must call return from the action passed to Dispatcher.Invoke.

0
source share

All Articles