WCF

WCF Examples

WCF

WCF Projects

WCF Project

adplus-dvertising
Events
Previous Home Next

Events provide the client or clients to be notified about something that occurred on the service side. The event can result from a direct client call, or it can be the result of something the service monitors. vent-handling operations must have a void return type, should not have any outgoing parameters, and should be marked as one-waye.

The service firing the event is called the publisher, and the client receiving the event is called the subscriber. Events are a required feature in almost any type of application.

interface IMyEvents
{
[OperationContract(IsOneWay = true)]
void Evantoperation1( );
[OperationContract(IsOneWay = true)]
void Evantoperation2(int number);
[OperationContract(IsOneWay = true)]
void Evantoperation3(int number,string text);
}

Example of Events management using delegates:

enum EventExample
{
Event1 = 1,
Event2 = 2,
Event3 = 4,
AllEvents = Event1|Event2|Event3
}
[ServiceContract(CallbackContract = typeof(IMyEvents))]
interface IMyContract
{
[OperationContract]
void operation( );
[OperationContract]
void Subscribe(EventExample EExample);
[OperationContract]
void Unsubscribe(EventExample EExample);
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
class MyPublisher : IMyContract
{
static GenericEventHandler GEventhandlr1 = delegate{};
static GenericEventHandler<int> GEventhandlr2  = delegate{};
static GenericEventHandler<int,string> GEventhandlr3 = delegate{};
public void Subscribe(EventExample EExample)
{
IMyEvents subscriber =  OperationContext.Current.
GetCallbackChannel<IMyEvents>( );
if((EExample & EventExample.Event1) == EventExample.Event1)
{
GEventhandlr1 += subscriber.OnEvent1;
}
if((EExample & EventExample.Event2) == EventExample.Event2)
{
GEventhandlr2 += subscriber.OnEvent2;
}
if((EExample & EventExample.Event3) == EventExample.Event3)
{
GEventhandlr3 += subscriber.OnEvent3;
}
}
public void Unsubscribe(EventExample EExample)
{
//Similar to Subscribe( ) but uses -=
}
public static void FireEvent(EventExample EventExample)
{
switch(EventExample)
{
case EventExample.Event1:
{
GEventhandlr1( );
return;
}

case EventExample.Event2:
{
GEventhandlr2(42);
return;
}
case EventExample.Event3:
{
GEventhandlr3(42,"Hello");
return;
}
default:
{
throw new InvalidOperationException("Unknown event type");
}
}
}
public void operation( )
{...}
}
Previous Home Next