如何退出(停止)我的调度员?

Nor*_*ick 8 c# wpf dispatcher

当用户点击按钮时,我想停止在main()中启动的调度程序.

    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();
    }
Run Code Online (Sandbox Code Playgroud)

当我运行此代码时,我在以下位置停止时收到以下错误消息onFrameEventFocusCam:

  Error-Message: Thread was interrupted from a waiting state.
Run Code Online (Sandbox Code Playgroud)

Tho*_*que 2

当您调用时,它会导致调度程序异步BeginInvokeDispatcher关闭;它仍然需要在关闭之前完成当前调度程序帧的处理。但是,由于您在循环中等待调度程序关闭,因此当前帧永远不会完成,因此调度程序无法完成关闭。相反,您可以订阅该事件来检测调度程序何时关闭。ShutdownFinished

至于您遇到的错误onFrameEventFocusCam,我认为这是因为调度程序正在关闭,因此它无法处理Invoke; 从文档中:

一旦关闭过程开始,队列中所有待处理的工作项都会中止。

我不确定你想做什么,但关闭主调度程序很可能不是这样做的方法,因为它会有效地停止应用程序......