In Winforms, all controls have an InvokeRequired
property, that returns true if I have to call .[Begin]Invoke on the control in order to modify it.
In WPF, there is an apparently similar construct in DispatcherObject.CheckAccess()
and Dispatcher.CheckAccess()
, but I am frightened by the EditorBrowsable(EditorBrowsableState.Never)
attribute. When I disable editor browsing like this, I use it to means "You should not be doing this. No, really. If this is required solve your immediate problem, you have mis-designed your solution to your overarching problem." On the other hand, the only alternative I've found (and, in fact, my original solution) is Thread.CurrentThread.ManagedThreadId == 1
. (It's horrible. And it doesn't work in the generic case. I know. It does work for my limited uses, though.)
The MSDN documentation is silent on the presence of and reasoning behind the EditorBrowsable
attribute. Does it indeed mean "do not use this", as it would if I had typed it, or does it have some other less prohibitive meaning?
BeginInvoke(DispatcherPriority, Delegate, Object) Executes the specified delegate asynchronously at the specified priority and with the specified argument on the thread the Dispatcher is associated with.
Invoke(Action, DispatcherPriority, CancellationToken)Executes the specified Action synchronously at the specified priority on the thread the Dispatcher is associated with.
A dispatcher is often used to invoke calls on another thread. An example would be if you have a background thread working, and you need to update the UI thread, you would need a dispatcher to do it.
In WPF, you can call Dispatcher.Invoke
regardless of your current thread, and it'll handle the call accordingly - if you're already on the right thread, it'll just invoke your code, and it uses CheckAccess
to handle this behaviour.
For a BeginInvoke
the thread you're currently on is irrelevant: BeginInvoke
is always asyncronous, and the order of execution is dependant on the priority of the item you add to the dispatcher's queue.
If you weren't supposed to use the method at all, it wouldn't be public: the intent of that attribute is only to hide the member from mechanisms such as Intellisense and other editor-browsers. You don't typically need to use Dispatcher.CheckAccess()
yourself, which is probably why it's marked as non-browsable, but the wisdom of this is something we can only guess at (unless Eric Lippert is watching ;-)
In summary: just call Dispatcher.Invoke
and don't worry about CheckAccess
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With