[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Reentrant)]
I want to use single instance but it won't work.
It fires all the events to the last subscribed client. Please help.The sample has InstanceContextMode.PerSession
, not InstanceContextMode.PerCall
. Each subscribed client is associated with a separate instance of MyService
. Each of these instances has a member field _callbackInstance
which holds the reference to its particular client's callback channel. All the instances of MyService
are associated into a "chat room" via the static event Broadcast
, and when a particular client says something, the code iterates through the invocation list of the static event to broadcast to each subscribed client.
If you make MyService
a singleton, _callbackInstance
only contains the last subscribed client's callback channel, which is why you see the behaviour you describe.
In order to make the service class operate correctly as a singleton instance, you would have to replace _callbackInstance
with a collection containing all the callback channels for the subscribed clients, and manage the additions and deletions from this collection yourself as clients arrived and left. Broadcasting would then involve iterating this collection. The drawback of this approach is that multiple clients may be calling the service concurrently, and you therefore need explicitly to synchronise access to the members of the class in order to ensure thread-safety and correct behaviour.
Thanks to Chris, I found this example showing how to handle multiply callback subscribers when using InstanceContextMode.Single
.
The example showing how to manage a dictionary (list is also possible) of callback channels.
Igal.
精彩评论