我有一个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尝试了这个想法,但客户端被阻止了。
有人有其他想法吗?
答案 0 :(得分:1)
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();
}
}