Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I exit (stop) my Dispatcher?

Tags:

c#

wpf

dispatcher

I would like to stop my dispatcher which has been started in the 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 following error message while it is stopped in the onFrameEventFocusCam:

  Error-Message: Thread was interrupted from a waiting state.
like image 714
Norick Avatar asked Jul 18 '14 09:07

Norick


1 Answers

When you call BeginInvokeDispatcher, it causes the dispatcher to shut down asynchronously; it still needs to finish processing the current dispatcher frame before it shuts down. But since you're waiting in a loop for the dispatcher to shut down, the current frame never completes, so the dispatcher can't complete the shutdown. Instead, you can subscribe to the ShutdownFinished event to detect when the dispatcher shuts down.

As for the error you're getting in onFrameEventFocusCam, I think this is because the dispatcher is shutting down, so it can't process the Invoke; from the documentation:

Once the shutdown process begins, all pending work items in the queue are aborted.

I'm not sure what you're trying to do, but shutting down the main dispatcher is very probably not the way to do it, as it will effectively stop the app...

like image 74
Thomas Levesque Avatar answered Sep 30 '22 02:09

Thomas Levesque