WCF Subscriber notifies subscribers

This is my WCF service. I want to notify several subscribers of some updates and do it asynchronously. How can I do it?

// Callback contract public interface IMyServiceCallback { [OperationContract] void Notify(String sData); } public class MyService:IMyService { List<IMyServiceCallback> _subscribers = new List<IMyServiceCallback>(); // This function is used to subscribe to service. public bool Subscribe() { try { IMyServiceCallback callback = OperationContext.Current.GetCallbackChannel<IMyServiceCallback>(); if (!_subscribers.Contains(callback)) _subscribers.Add(callback); return true; } catch { return false; } } // this function is used to notify all the subsribers // I want ForEach to be asynchronous. public void OnGetMsg(string sData) { _subscribers.ForEach( callback => { if (((ICommunicationObject)callback).State == CommunicationState.Opened) { callback.Notify(sData); //THIS OPERATION } else { _subscribers.Remove(callback); } }); } } 
+4
source share
1 answer

You can put it in the thread pool:

  ThreadPool.QueueUserWorkItem(o => callback.Notify(sData)); 

Just keep in mind that this can clog your flow when you have a lot of bad subscribers. You probably want to catch the exceptions and remove the callback when it failed.

Refresh . If you do not want to use the .NET thread pool, you can either collapse your own, or, for example, use SmartThreadPool

+1
source

All Articles