WCF正确回调到多个客户端

时间:2018-02-28 22:39:01

标签: c# performance wcf duplex

所以我有一个控制一堆测量仪器和几个摄像头的wcf服务。我做了它,所以每次相机准备好位图时服务都会回调连接的客户端。代码都正常运行但是我后来害怕稳定性问题,因为我基本上只有一个用每个新连接更新的合同列表,我通过捕获异常来删除旧的...我觉得不太自信在那。

无论如何这里是代码:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class ServiceCamera : IServiceCamera
{
    private static Dictionary<string,ICamera> Cameras = new Dictionary<string, ICamera>();
    static List<IMyContractCallback> cblist = new List<IMyContractCallback>();
    private void camera_ImageReady(object sender, Bitmap bitmap2)
    {
        for (var i = 0; i < cblist.Count; i++)
        {
            try
            {
                if (cblist[i] != null)
                {
                    cblist[i].ServiceImageReady(bitmap2);
                }
            }
            catch (Exception ex)
            {
                cblist.RemoveAt(i);
            }
        }
    }
    public void Connect()
    {
        callback = OperationContext.Current.GetCallbackChannel<IMyContractCallback>();
        cblist.Add(OperationContext.Current.GetCallbackChannel<IMyContractCallback>());
        ICamera camera;
        if (Cameras.ContainsKey(OperationContext.Current.EndpointDispatcher.EndpointAddress.Uri.Segments.Last()))
        {
            camera = Cameras[OperationContext.Current.EndpointDispatcher.EndpointAddress.Uri.Segments.Last()];
            if (!camera.IsConnected)
            {
                camera.ImageReady -= camera_ImageReady;
                camera.Connect();
                camera.ImageReady += camera_ImageReady;
            }
        }
        else
        {
            camera = (ICamera)InstrumentLoader.Factory.GetNamed(OperationContext.Current.EndpointDispatcher.EndpointAddress.Uri.Segments.Last());
            Cameras.Add(OperationContext.Current.EndpointDispatcher.EndpointAddress.Uri.Segments.Last(), camera);
            camera.ImageReady -= camera_ImageReady;
            camera.Connect();
            camera.ImageReady += camera_ImageReady;
        }
    }
}

public interface IMyContractCallback
{        
    [OperationContract(IsOneWay = true)]
    void ServiceImageReady(Bitmap bitmap);        
}

这是我对双面wcf的第一次体验,并且觉得我可以在其上进行很多改进。我有一种感觉,我尝试的大部分内容都可以通过更改InstanceContextMode来完成。

0 个答案:

没有答案