Reputation: 37172
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);
}
});
}
}
"MSDN: WCF Publisher/Subscriber Client crashing" is strongly related to my problem.
I have followed Mini Webcast while creating this service.
Upvotes: 4
Views: 964
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