Pratik Deoghare
Pratik Deoghare

Reputation: 37172

WCF Notify subscribers asynchronously

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

// 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);
                }
            });
   }
}

Upvotes: 4

Views: 964

Answers (1)

ChrisWue
ChrisWue

Reputation: 19020

You can put it to the thread pool:

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

Just be aware that it might clog up your threadpool when you have many bad subscribers. You probably want to catch exceptions and remove the callback when it failed.

Update: If you don't want to use the .NET thread pool then you can either roll your own or for example use the SmartThreadPool

Upvotes: 1

Related Questions