I am new to WPF and have a question regarding dispatcher and Delegate.Invoke.
In a windows forms application, we can use the invoke method to make changes to UI controls from other threads. This works because invoke “executes the specified delegate on the thread that owns the control’s underlying window handle” (as per msdn).
My question is:
-
Why doesn’t
Invokework on WPF? It should be allowed to make changes to UI as the thread that owns the UI control gets to execute the delegate, but still it throws a runtime exception that “a thread is trying to modify an object that is owned by a different thread”. -
How does the dispatcher manage to make changes to WPF controls while
Invokefails? -
Is it possible to do cross thread programming in WPF without using dispatcher or background worker?
It works fine, but perhaps you’re not using it correctly. I suggest you read the documentation
Perhaps you created a UI object on a worker thread, then tried to add it to the main UI on the UI thread ? Without seeing your code, it’s only a guess…
This question is not very clear, but it’s probably related to the first question anyway…
If you need to manipulate the UI from a worker thread, you have to use the dispatcher.
BackgroundWorkeralso uses the dispatcher (indirectly, through theISynchronizationContextinterface) to raise events on the UI thread. There’s no way around it.