With reference from MSDN ConcurrentBag<T>::TryTake
method.
Attempts to remove and return an object from the
ConcurrentBag<T>
.
I am wondering about on which basis it removes object from the Bag, as per my understanding dictionary add and remove works on the basis of HashCode
.
If concurrent bag has nothing to do with the hashcode, what will happen when the object values get change during the add and remove.
For example:
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"});
}
// have change the name from student.FirstName="khan";
// property of the object has been changed
Now the object properties values has been changed.
What will be the behavior of when I remove ConcurrentBag<T>::TryTake
method? how it will track the object is same when added?
Code:
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
}
}