Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何存储到WCF服务的所有连接?_C#_.net_Wcf - Fatal编程技术网

C# 如何存储到WCF服务的所有连接?

C# 如何存储到WCF服务的所有连接?,c#,.net,wcf,C#,.net,Wcf,我的WCF服务使用回调。为了能够给所有客户打电话,我使用了如下方法: [ServiceBehavior (InstanceContextMode = InstanceContextMode.PerSession)] class Svc { // stores all connections private static List<Svc> Connections = new List<Svc> (); // callback for this i

我的WCF服务使用回调。为了能够给所有客户打电话,我使用了如下方法:

[ServiceBehavior (InstanceContextMode = InstanceContextMode.PerSession)]
class Svc
{
    // stores all connections
    private static List<Svc> Connections = new List<Svc> ();

    // callback for this instance
    private ICallback Cb;

    public Svc ()
    {
        Cb = OperationContext.Current.GetCallbackChannel<ICallback> ();
        Connections.Add (this);
    }

    // ... lots of other code that uses or updates the list of connections
}
public Svc()
{
    this.CallbackChannel = OperationContext.Current.GetCallbackChannel<ICallback>();

    // The static 'Instance' property returns the singleton
    SvcActiveInstanceContainer.Instance.Add(this);
}
[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession)]
类Svc
{
//存储所有连接
私有静态列表连接=新列表();
//此实例的回调
私人ICallback Cb;
公共Svc()
{
Cb=OperationContext.Current.GetCallbackChannel();
连接。添加(此);
}
//…许多其他使用或更新连接列表的代码
}
这样做对吗

我这样问是因为我在与上述方法中的一个明显的设计问题作斗争。我尝试将许多常用代码,包括
静态列表
移动到一个可以被我的所有WCF服务使用的通用基类。但在派生时,此列表在所有子类之间共享


然后,我试图通过使基类泛型来避免这种不必要的共享(
Svc
,这意味着每个子类都有自己的静态成员),但这会导致其他麻烦,而且不是一种干净的设计。

是的,这是存储对客户端的引用以向所有客户端发送回调的正确方法。我不在服务中存储CallbackChannel对象,而是存储OperationContext实例


对于您的另一个问题:您可以提取代码来管理连接到单独类的客户端列表,并在服务中使用该类的实例。

当您需要以集中方式存储全局状态时,请使用单例模式

在您的情况下,它可能如下所示:

[ServiceBehavior (InstanceContextMode = InstanceContextMode.PerSession)]
class Svc
{
    // stores all connections
    private static List<Svc> Connections = new List<Svc> ();

    // callback for this instance
    private ICallback Cb;

    public Svc ()
    {
        Cb = OperationContext.Current.GetCallbackChannel<ICallback> ();
        Connections.Add (this);
    }

    // ... lots of other code that uses or updates the list of connections
}
public Svc()
{
    this.CallbackChannel = OperationContext.Current.GetCallbackChannel<ICallback>();

    // The static 'Instance' property returns the singleton
    SvcActiveInstanceContainer.Instance.Add(this);
}
publicsvc()
{
this.CallbackChannel=OperationContext.Current.GetCallbackChannel();
//静态“Instance”属性返回单例
svctiveInstanceContainer.Instance.Add(此);
}
相关资源:


对不起,我不明白这有什么帮助?共享变量的问题没有得到解决。而且该服务不能以单例开始(
PerSession
)。