开发者

Difference in Event Handling in Silverlight and WPF - Thread Affinity issues

I have been developing a Lync Silverlight application in Silverlight and now I am trying to shift it to WPF.

Howe开发者_如何学JAVAver, I am facing some thread affinity issues. For example I display the Lync client's state on my page in a textblock, and so in my code behind have wired a state changed event handler, that writes the new state into the textblock whenever the state of Lync client changes.

Now, this worked perfectly in silverlight but seemingly is not allowed in WPF. Now my questions are:

  1. How come it works in Silverlight bt not in WPF, even though Silverlight is supposed to be a subset of WPF?

  2. Thread affinity is an important concept and I know we can use invoke dispatcher, but doesn't it just beat the concept of asynchronous programming in form of event handlers and callbacks?

  3. I have a button defined in my XAML page, and the click event handler defined on it can access other UI elements, it does not suffer the problem outlined above.

    But if I define a LyncClient instance in my code-behind, event handlers defined on it cannot access the UI elements. Why so, I detected no such difference between UIElements and other objects in Silverlight?


Based on above comments, I'll suggest the following "answer"...

I would guess it is more likely than not that there is some sort of different in the way that the SL API was written than that of the WPF api. That could explain the difference in the thread that is used when the API issues the callback. To verify this, you could:

  1. Ask MS directly
  2. Put some diagnostics code in your callback method to log the thread ID and compare that to the main thread of the application. Do this for both SL and WPF to see if they are the same or different threads.
  3. Open the assemblies in Reflector to inspect how each API was written.

In terms of handling this specific situation, in your callback, you could:

  1. Get the dispatcher object (different for SL than WPF) and always issue UI updates through Dispatcher.Invoke.
  2. Use databinding and INotifyPropertyChanged to insulate the UI from the property. You could delcare a property on a ViewModel or in the code behind. Then bind the UI's textbox to that property. Databinding has some smarts in it that will automatically marshal property changes to the correct thread (in most cases anyway).

Hope that helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜