【发布时间】:2016-09-30 23:03:20
【问题描述】:
我获得了由 Windows 服务托管的 wcf 服务。 Windows 服务侦听 USB 驱动器(移除和插入。 现在我想通知客户。
我尝试先从 windows 服务调用 wcf 服务中的静态方法 然后我通过
调用回调方法OperationContext.Current.GetCallbackChannel<ICallback>()
但 OperationContext.Current 始终为空。似乎我在错误的线程/上下文中。
然后尝试在 wcf 服务中声明一个静态事件,在 wcf 中注册它并从 wcf 服务中的 windows 服务调用一个静态方法,然后触发该事件:
//WCF Service
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class WCFService : IService
{
public static event EventHandler<EventArgs> StatusChanged;
public Service()
{
StatusChanged += OnStatusChanged;
}
private void OnStatusChanged(object sender, EventArgs eventArgs)
{
// still not in the correct thread here?
// OperationContext.Current is null
OperationContext.Current.GetCallbackChannel<ILocalLicenceBackendServiceCallback>().ServiceStateChanged();
}
public static void ChangeStatus()
{
if (StatusChanged != null)
StatusChanged(null,EventArgs.Empty);
}
}
//Windows Service
public partial class WindowsService : ServiceBase
{
private void OnStatusChanged()
{
WCFService.ChangeStatus();
}
}
..仍然无法正常工作。那么我该如何做到这一点,通过 wcf 回调将信息从 Windows 服务传递到客户端。
【问题讨论】:
-
您只能在服务操作内部进行回调,该服务操作最初是对您的服务的客户端调用(
OperationContext.Current仅在服务操作内部不为空)。您的OnStatusChanged事件处理程序不会在 WCF 服务操作的上下文中执行。您是否已经研究过关于 SO 的其他“发布订阅 wcf”文章?那里有很多信息。
标签: c# wcf callback windows-services