WCF回调通知用户界面

问题描述

| 我有一个wcf回调服务和以下情况: 客户端向服务发送请求,并修改数据库中矩形的颜色,服务通知该颜色已更改,现在我要在回调通知方法中为选中的矩形着色颜色: 这是当我单击矩形时调用方法
private void ChangeRectangleState_Single(object sender,RoutedEventArgs e)
{
    Path mc = (Path)sender;
    String name = mc.Name;

    flag_macaz = colorClass.getRectangleColor(mc.Name+\"_a\",rectangleServiceClient);
    ColorClass.changeRectangleColor(flag_rectangle,macazServiceClient,mc.Name+\"_a\");
}

public void RectangleServiceCallback_ClientNotified(objectsender,Rectangle NotifiedEventArgs e)
{
   String name = e.RectangleName;
   object wantednode_a = Window.FindName(e.RectangleName);
   Path rectangle = wantednode_a as Path;
   if (e.RectangleColor == 1)
   {
       rectangle.fill=...
   }
   else
        if (e.RectangleColor == 0)
   {
       rectangle.fill=...
   }
}
但是我收到错误消息“调用线程无法访问该对象,因为其他线程拥有它。” 我从http://www.switchonthecode.com/tutorials/working-with-the-wpf-dispatcher尝试了这个想法,但是客户端被阻止了。 有人有其他想法吗?     

解决方法

        WCF线程无法直接调用UI线程。 您需要从WCF线程中触发事件,然后在UI线程中进行订阅。然后在您的UI事件处理程序中输入以下内容:
    this.albumArt.InvokeIfRequired(() => this.SetBackgroundColor());
其中
InvokeIfRequired
是扩展方法:
public static void InvokeIfRequired(this Control control,Action action)
{
    if (control.InvokeRequired)
    {
        control.Invoke(action);
    }
    else
    {
        action();
    }
}