Search code examples
wpfmultithreadingdispatcher

WPF - Dispatcher PushFrame()


I'm trying to call Dispatcher.PushFrame() from several different thread but encounter an error:

Must create DependencySource on same Thread as the DependencyObject.

Here is a code snippet:

_lockFrame = new DispatcherFrame(true);
Dispatcher.PushFrame(_lockFrame);

When I tried:

Dispatcher.CurrentDispatcher.Invoke(
    DispatcherPriority.Normal,
    new Action(() => _lockFrame = new DispatcherFrame(true));
Dispatcher.PushFrame(_lockFrame);

I get the error:

Objects must be created by the same thread.

What is the approach for pushing multiple frames into the Dispatcher from different threads?


Solution

  • Each thread has its own dispatcher object - returned by Dispatcher.CurrentDispatcher

    The approach would be to cache the target dispatcher object once by calling the above method on the UI Thread. Then use _cachedObj.Invoke like you have - to marshal it across to the right thread.

    WPF UI has 'thread affinity' - UI can only be accessed by the thread that creates it.

    Update: Not sure of what you're trying to achieve. But the following code-snippet worked for me.

        private Dispatcher _dispatcher;
        private DispatcherFrame _lockFrame;
        public Window1()
        {
            InitializeComponent();
    
            _dispatcher = Dispatcher.CurrentDispatcher;
    
            // the other thread
            Thread t = new Thread(
                (ThreadStart)delegate
                {
    
                    _dispatcher.Invoke(
                        (Action)delegate
                        {
                            var frame = CreateNewFrame();
                            Dispatcher.PushFrame(frame);
                        });
                });
            t.Start();