这是我的WCF服务。我想通知多个订阅者 一些更新,并以异步方式进行。我怎么做?
// 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);
}
});
}
}
答案 0 :(得分:1)
您可以将它放到线程池中:
ThreadPool.QueueUserWorkItem(o => callback.Notify(sData));
请注意,当您有许多不良订阅者时,它可能会阻塞您的线程池。您可能希望捕获异常并在失败时删除回调。
更新:如果您不想使用.NET线程池,那么您可以自己滚动,也可以使用SmartThreadPool