I'm trying to set up a simple duplex service whereby clients connect to the server. Any connected client may execute the BookAdded
service operation. When this occurs the server is supposed to raise a callback on all connected clients to notify them of the change.
The callback seems to be working fine except that the callback operation needs to run something on the UI thread using Dispatcher.BeginInvoke
.
In my case Console.WriteLine("Callback thread")
gets executed buy Console.WriteLine("Dispatcher thread")
does not. What is the reason for this?
My service contract:
public interface ICallback
{
[OperationContract(IsOneWay = true)]
void BookAdded(string bookId);
}
[ServiceContract(
CallbackContract = typeof(ICallback),
SessionMode = SessionMode.Required)]
public interface IService
{
[OperationContract]
bool BookAdded(string bookId);
}
My service implementation:
[ServiceBehavior(
UseSynchronizationContext = false,
InstanceContextMode = InstanceContextMode.PerSession,
ConcurrencyMode = ConcurrencyMode.Reentrant)]
public class MyService : IService
{
public bool BookAdded(string bookId)
{
try
{
Console.WriteLine("Client Added Book " + bookId);
foreach (ICallback callback in connectedClients)
{
callback.BookAdded(bookId);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return true;
}
}
My client implementation:
[CallbackBehavior(UseSynchronizationContext = false, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class MyCallBack: ICallback, IDisposable
{
private Dispatcher theDispatcher;
private InstanceContext context;
private WcfDuplexProxy<IService> proxy;
[ImportingConstructor]
public MyCallBack()
{
theDispatcher = Dispatcher.CurrentDispatcher;
context = new InstanceContext(this);
proxy = new WcfDuplexProxy<IService>(context);
proxy.Connect();
}
public IService Service
{
get
{
return proxy.ServiceChannel;
}
}
public void CallServiceOperation()
{
Service.BookAdded("BOOK1234");
}
public void BookAdded(string bookId)
{
Console.WriteLine("Callback thread");
theDispatcher.BeginInvoke(new Action(() => { Console.WriteLine("Dispatcher thread"); }));
}
public void Dispose()
{
Service.Disconnect();
proxy.Close();
}