我看到 WCF 不直接使用事件,而是使用 OneWay 委托(delegate)调用,但是有人可以向我展示一个简单的示例来说明如何执行此操作吗?
这是我现在的设置:
[OperationContract(IsOneWay = true)]
void OnGetMapStoryboardsComplete(object sender, List<Storyboard> results);
最佳答案
假设您的回调协定接口(interface)被称为IMyServiceCallback
,您的服务将在它想要引发事件时执行以下代码:
IMyServiceCallback callback = OperationContext.Current.GetCallbackChannel<IMyServiceCallback>();
callback.OnGetMapStoryboardsComplete(...);
我找到了 this article非常有帮助。它描述了 transient 事件系统和持久事件系统,IMO 中的任何一个都应该满足任何和所有事件场景。
HTH
设置回调合约:
interface IMyServiceCallback
{
[OperationContract(IsOneWay = true)]
void OnGetMapStoryboardsComplete(object sender, List<Storyboard>);
}
然后你需要在你的服务契约(Contract)上指明它正在使用这个回调:
[ServiceContract(CallbackContract = typeof(IMyServiceCallback))]
interface IMyService
{
// ...
}
完成该操作并实现您的服务后,创建对该服务的引用。然后,客户端必须包含一个实现 IMyServiceCallback
的类:
class EventHandler : IMyServiceCallback
{
public void OnGetMapStoryBoardsComplete(object sender, List<Storyboard>)
{
// Do whatever needs to be done when the event is raised.
}
}
当您从客户端连接到服务时,您需要向其传递一个InstanceContext
,该InstanceContext
是使用对将处理事件的对象的引用构建的:
EventHandler eventHandler = new EventHandler();
MyServiceClient client = new MyServiceClient(new InstanceContext(eventHandler));
这有意义吗?
关于WCF 事件声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1143743/