WCF 事件声明 [英] WCF Event Declaration
问题描述
我看到 WCF 不直接使用事件,而是使用 OneWay 委托调用,但有人可以向我展示一个简单的示例来说明如何执行此操作吗?
I see that WCF doesn't directly use events and instead uses OneWay delegate calls, but can someone show me a simple example on how to do this?
这是我现在的设置:
[OperationContract(IsOneWay = true)]
void OnGetMapStoryboardsComplete(object sender, List<Storyboard> results);
推荐答案
假设您的回调协定接口名为 IMyServiceCallback
,您的服务将在想要引发事件时执行以下代码:>
Assuming your callback contract interface is called IMyServiceCallback
, your service would execute the following code when it wanted to raise the event:
IMyServiceCallback callback = OperationContext.Current.GetCallbackChannel<IMyServiceCallback>();
callback.OnGetMapStoryboardsComplete(...);
我发现这篇文章很有帮助.它描述了一个瞬态事件系统和一个持久事件系统,其中任何一个都应满足 IMO 的任何和所有事件场景.
I found this article very helpful. It describes a transient event system and a persisted event system, either of which should satisfy any and all event scenarios, IMO.
HTH
设置回调合约:
interface IMyServiceCallback
{
[OperationContract(IsOneWay = true)]
void OnGetMapStoryboardsComplete(object sender, List<Storyboard>);
}
然后你需要在你的服务合同上指明它正在使用这个回调:
Then you need to indicate on your service contract that it is using this callback:
[ServiceContract(CallbackContract = typeof(IMyServiceCallback))]
interface IMyService
{
// ...
}
完成此操作并实施服务后,请创建对服务的引用.然后客户端必须包含一个实现 IMyServiceCallback
的类:
Once you have done that and implemented your service, create a reference to the service. The client will then have to include a class that implements IMyServiceCallback
:
class EventHandler : IMyServiceCallback
{
public void OnGetMapStoryBoardsComplete(object sender, List<Storyboard>)
{
// Do whatever needs to be done when the event is raised.
}
}
当您从客户端连接到服务时,您需要将一个 InstanceContext
传递给它,该InstanceContext
使用对将处理事件的对象的引用构建:
When you connect from the client to the service you need to pass it an InstanceContext
built with a reference to the object that will handle the events:
EventHandler eventHandler = new EventHandler();
MyServiceClient client = new MyServiceClient(new InstanceContext(eventHandler));
有意义吗?
这篇关于WCF 事件声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!