参考MSDN ConcurrentBag<T>::TryTake
方法
尝试从ConcurrentBag中删除并返回一个对象。
我想知道它在哪个基础上从Bag中移除对象,根据我的理解字典添加和删除基于HashCode的工作。
如果并发包与hascode无关,那么在添加和删除期间对象值发生变化时会发生什么。
forexample。
public static IDictionary<string, ConcurrentBag<Test>> SereverConnections = new ConcurrentDictionary<string, ConcurrentBag<Test>>();
public class Student
{
public string FirstName{get;set;}
Student student=new Student();
SereverConnections.add(student.FirstName{"bilal"});
}
//从
更改名称//student.FirstName="khan"; property of the object has been changed
现在对象属性值已更改,
删除ConcurrentBag<T>::TryTake
方法时的行为是什么?添加后如何跟踪对象是一样的?
代码:
public class Test
{
public HashSet<string> Data = new HashSet<string>();
public static IDictionary<string, ConcurrentBag<Test>> SereverConnections = new ConcurrentDictionary<string, ConcurrentBag<Test>>();
public string SessionId { set; get; }
public Test()
{
SessionId = Guid.NewGuid().ToString();
}
public void Add(string Val)
{
lock (Data) Data.Add(Val);
}
public void Remove(string Val)
{
lock (Data) Data.Remove(Val);
}
public void AddDictonary(Test Val)
{
ConcurrentBag<Test> connections;
connections=SereverConnections["123"] = new ConcurrentBag<Test>();
connections.Add(this);
}
public void RemoveDictonary(Test Val)
{
SereverConnections["123"].TryTake(out Val);
}
public override int GetHashCode()
{
return SessionId.GetHashCode();
}
}
//calling
class Program
{
static void Main(string[] args)
{
Test test = new Test();
test.AddDictonary(test);
test.RemoveDictonary(test);//remove test.
test.RemoveDictonary(new Test());//new object
}
}