Annymmor A
Annymmor A

Reputation: 1

WCF Callback notify user interface

I have a wcf callback service and the following scenario:

A client send a request to the service, and modify the color of a rectangle in the database, the service notifies it that the color has changed, and I want now in the callback notified method, to color the rectangle that was clicked with the chosen color:

Here is the method which is invoked when I click on rectangle

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=...
   }
}

But I get the error "The calling thread cannot access this object because a different thread owns it."

I have tried the idea from http://www.switchonthecode.com/tutorials/working-with-the-wpf-dispatcher but the client get blocked.

Does anybody has other idea?

Upvotes: 0

Views: 683

Answers (1)

ChrisF
ChrisF

Reputation: 137158

The WCF thread can't call the UI thread directly.

You'll need to fire an event from the WCF thread and subscribe to it in the UI thread. Then in your UI event handler have something like:

    this.albumArt.InvokeIfRequired(() => this.SetBackgroundColor());

where InvokeIfRequired is an extension method:

public static void InvokeIfRequired(this Control control, Action action)
{
    if (control.InvokeRequired)
    {
        control.Invoke(action);
    }
    else
    {
        action();
    }
}

Upvotes: 1

Related Questions