0

Help me pls to understand how does ConcurrentDictionary work? I have this:

UsersOnlineClass client;
if (UsersOnlineDictionary.TryGetValue(comClientID, out client)) { }

I have to change some value in client and save changes in ConcurrentDictionary. As will be right?

UsersOnlineClass updatedClient = new UsersOnlineClass();
updatedClient = client; //make copy
updatedClient.someInt = -1;
if (UsersOnlineDictionary.TryUpdate(client.Client_id, updatedClient, client)) { }

or I can just do so, and that will be enough?

client.someInt = -1;
  • Just test and you will see. Since `UsersOnlineClass` seems to be reference type, you can use both ways, although one liner is easier to understand – dotnetom Jan 25 '15 at 19:26
  • 1
    Is `UsersOnlineClass` a `class` or a `struct`? If a class, `updatedClient = client; //make copy` will not actually copy the class. If a struct, you don't need to copy it locally, because it will already have been copied out of the dictionary. ([See here on `struct assignment`](https://msdn.microsoft.com/en-us/library/saxz13w4.aspx)). – dbc Jan 25 '15 at 20:08

1 Answers1

2

If UsersOnlineClass is a class, your code is fine (as long as "someInt" is thread-safe), since client then is a reference to the object in the dictionary. If UsersOnlineClass is a struct, however, you must do as in your example code, since client will then be a copy for what's in the dictionary.

Dan Byström
  • 9,067
  • 5
  • 38
  • 68