简体   繁体   English

wcf服务中的字典未更新

[英]dictionary is not updating in wcf service

So, I have a very simple WCF client-server app. 因此,我有一个非常简单的WCF客户端-服务器应用程序。 The thing is, the service gets messages from the client and it also receives pending messages requests. 问题是,服务从客户端获取消息,并且还接收未决的消息请求。 However, it does not return a message to client. 但是,它不会向客户端返回消息。 Instead it shows this part: Pending messages does not contain key {id} although the id is fine 相反,它显示了这一部分: 待处理的消息不包含密钥{id},尽管id很好

private Dictionary<int, List<Message>> pendingMessages =
    new Dictionary<int, List<Message>>();

public IEnumerable<Message> GetMessages(int id)
{
    Console.WriteLine($"New request from {id}");
    List<Message> messages;

    if (!pendingMessages.ContainsKey(id))
    {
        Console.WriteLine($"Pending messages does not contain key {id} ");
        return null;
    }

    messages = pendingMessages[id].ToList();
    pendingMessages[id].Clear();

    foreach (var msg in messages)
    {
        Console.WriteLine($"Returned message: ${msg.From}=>{msg.To}:{msg.Body}");
    }

    return messages;
}

public void SendMessage(Message msg)
{
    if (!pendingMessages.ContainsKey(msg.To))
    {
        pendingMessages.Add(msg.To,new List<Message>());
    }

    pendingMessages[msg.To].Add(msg);
    Console.WriteLine($"{msg.From}=>{msg.To}: {msg.Body}");
}

It is because the instance which process GetMessages differs from the instance which process SendMessage and you store your messages in local variable in your service object so different instance of the service class have different pendingMessages . 这是因为处理GetMessages的实例与处理SendMessage的实例不同,并且您将消息存储在服务对象的本地变量中,因此服务类的不同实例具有不同的pendingMessages

If you really want to make all calls to a single instance of your service you should change your service behavior. 如果您确实要对服务的单个实例进行所有调用,则应更改服务行为。 just add this attribute to your service 只需将此属性添加到您的服务

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]

After that just one instance of your service is used for all incoming calls. 之后,只有一个服务实例可用于所有来电。

If you want to know more read this . 如果您想了解更多的阅读

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM