简体   繁体   中英

dictionary is not updating in wcf service

So, I have a very simple WCF client-server app. 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

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 .

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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