【问题标题】:How to work with OUT-value in ConcurrentDictionary.TryGetValue?如何在 ConcurrentDictionary.TryGetValue 中使用 OUT-value?
【发布时间】:2015-01-25 19:19:37
【问题描述】:

请帮助我了解 ConcurrentDictionary 是如何工作的? 我有这个:

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

我必须更改 client 中的一些值并将更改保存在 ConcurrentDictionary 中。对吗?

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

或者我可以这样做,这就足够了?

client.someInt = -1;

【问题讨论】:

  • 只要测试一下就知道了。由于UsersOnlineClass 似乎是引用类型,因此您可以同时使用这两种方式,尽管一种更容易理解
  • UsersOnlineClassclass 还是 struct?如果是类,updatedClient = client; //make copy 不会实际复制该类。如果是结构,则不需要在本地复制它,因为它已经从字典中复制出来了。 (See here on struct assignment)。

标签: c# concurrentdictionary


【解决方案1】:

如果UsersOnlineClass 是一个class,那么你的代码就可以了(只要“someInt”是线程安全的),因为client 那么是对字典中对象的引用。但是,如果 UsersOnlineClassstruct,则必须按照示例代码中的方式进行操作,因为 client 将成为字典中内容的副本.

【讨论】:

    猜你喜欢
    • 2011-07-26
    • 1970-01-01
    • 2011-08-04
    • 1970-01-01
    • 1970-01-01
    • 2011-01-17
    • 1970-01-01
    • 1970-01-01
    • 2019-07-11
    相关资源
    最近更新 更多