Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/256.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# 这种方法是线程安全的吗_C#_Multithreading_Concurrentdictionary - Fatal编程技术网

C# 这种方法是线程安全的吗

C# 这种方法是线程安全的吗,c#,multithreading,concurrentdictionary,C#,Multithreading,Concurrentdictionary,低于线程的方法是安全的吗?我知道ConcurrentDictionary提供了TryRemove方法,但我只是不喜欢有一个变量作为我永远不会使用的值 ConcurrentDictionary<int, int> myDict = new ConcurrentDictionary<int, int>(); if (myDict.ContainsKey(1)) ((IDictionary<int, int>)myDict).Remove(1); Con

低于线程的方法是安全的吗?我知道ConcurrentDictionary提供了TryRemove方法,但我只是不喜欢有一个变量作为我永远不会使用的值

ConcurrentDictionary<int, int> myDict = new ConcurrentDictionary<int, int>();

if (myDict.ContainsKey(1))
    ((IDictionary<int, int>)myDict).Remove(1);
ConcurrentDictionary myDict=新建ConcurrentDictionary();
if(myDict.ContainsKey(1))
((IDictionary)myDict)。删除(1);

您的目标似乎是通过消除使用
out
参数来提高代码的清晰度。这是一个值得关注的问题,但使用
Remove
不是正确的方法

定义自己的助手方法:

static bool TryRemove<TKey, Value>(
      this ConcurrentDictionary<TKey, Value> dict, TKey key) {
 TValue value;
 return dict.TryRemove(key, out value);
}
静态bool TryRemove(
此ConcurrentDictionary命令(TKey){
t价值;
返回dict.TryRemove(键,输出值);
}

您的目标似乎是通过消除使用
out
参数来提高代码的清晰度。这是一个值得关注的问题,但使用
Remove
不是正确的方法

定义自己的助手方法:

static bool TryRemove<TKey, Value>(
      this ConcurrentDictionary<TKey, Value> dict, TKey key) {
 TValue value;
 return dict.TryRemove(key, out value);
}
静态bool TryRemove(
此ConcurrentDictionary命令(TKey){
t价值;
返回dict.TryRemove(键,输出值);
}

TryRemove被公开是有原因的。这是一个愚蠢的论点。TryRemove是访问数据最安全的方式。您将从中得到一个True/False的返回值,这让您知道是否应该处理out变量。如果您确实不喜欢在TryRemove之后将该变量放置在周围,那么只需对其进行范围限定,使其仅对该调用有效。@Katie这是可能的,但在C#中相当麻烦。为什么忽略存储在dictionary中的值?若答案是“我已经读过了”,那个么很可能你们的代码不是线程安全的。TryRemove被公开是有原因的。这是一个愚蠢的论点。TryRemove是访问数据最安全的方式。您将从中得到一个True/False的返回值,这让您知道是否应该处理out变量。如果您确实不喜欢在TryRemove之后将该变量放置在周围,那么只需对其进行范围限定,使其仅对该调用有效。@Katie这是可能的,但在C#中相当麻烦。为什么忽略存储在dictionary中的值?若答案是“我已经读过了”,那个么很可能你们的代码不是线程安全的。喜欢它比喜欢CLR给出的更好me@Servy是的,我是说,我更喜欢它me@Servy是的,我是说.NET