我正在尝试建立一个简单的双工服务,让客户端连接到服务器。任何连接的客户端都可以执行BookAdded
服务操作。发生这种情况时,服务器应该在所有连接的客户端上引发回调,以通知它们更改。
回调似乎工作正常,只是回调操作需要在 UI 线程上使用Dispatcher.BeginInvoke
.
在我的情况下Console.WriteLine("Callback thread")
执行购买Console.WriteLine("Dispatcher thread")
没有。这是什么原因?
我的服务合同:
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);
}
我的服务实现:
[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;
}
}
我的客户端实现:
[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();
}