Maybe I’m doing something wrong, but if I try your example, Visual Studio says “Cannot access non-static method ‘BeginInvoke’ in static context;” I also fail to see any static members for System.Windows.Threading.Dispatcher in the Silverlight API reference.
Am I missing something?
]]>One thing to note…you can just use Dispatcher.BeginInvoke(MyMethod). There is no need to take it from “Application.Current.RootVisual.Dispatcher” or store a second reference statically.
-Joel
http://joel.neubeck.net/
There are a number of good reasons why asynchronous communications should be decoupled from the user interface thread. Here are two of them:
(1) As asynchrononous RIAs increase in complexity, they eventually need a notification infrastructure for data changes. The issue that there might be N user interface elements that are affected when a piece of data changes. Trying to hardwire all of these updates will drive you nuts. (I’ve tried it.) It’s better for UI elements to register their interest in certain data items and then let the notifier take over. The notifier will probably flip to the UI thread and then enumerate over all the subscribers: not flip over for each individual subscriber, or expect each subscriber to flip the thread itself.
(2) Code reuse. In a lot of cases we end up developing multiple apps and product lines, even when it’s just a few different test apps that are used in house. Often we write chunks of functionality that get used in multiple apps: it’s usually better to put “the tough stuff” like concurrency control into the reusable parts (which don’t know how they’ll be reused) rather than re-write them in the code that does the reusing.
]]>Application.Current.RootVisual.Dispatcher
I’m not sure what you mean by “get at a ScriptObject or UIElement statically don’t seem to work off when you’re not in the UI Thread.”
If you are attempting to update a UIElement, presumably you’ve got a reference to it, at which point you can call CheckAccess and BeginInvoke if required. If you are attempting to BeginInvoke some arbitrary code on the UI thread, then you’ve got the static reference I listed above.
]]>However, you might not have a reference to a UIElement handy at the place where you want to switch to the UI Thread — I still think it’s good to have a Dispatcher squirreled away in a static field somewhere, because most of the obvious ways to get at a ScriptObject or UIElement statically don’t seem to work off when you’re not in the UI Thread.
Personally, I like having ‘choke points’ in my apps that let me control concurrency on an app-wide basis. It took me less than half an hour for me to adjust to the changes between beta 2 and beta 1 because I only needed to change one method… It’s much better to have a standard method you call rather than to grasp for whatever random UIElement you can find in a situation.
]]>