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
}
}
ConcurrentBag
has no relationship, itself, with any dictionary-like data structure. So I'm really not sure what you're trying to ask here.TryTake
attempts to remove an object from the bag. NeitherTryTake
norAdd
have any need to "inspect" the object more thoroughly (such as viaGetHashCode
). They can just treat the objects as opaque "things" that they take in or hand out. – EnterectomyConcurrentBag<T>
is not simply a thread-safe linked list. It is a collection of thread-local linked lists. It returns the first node of the current thread's linked list, if there is any, otherwise it steals an item from another thread's local linked list. – Comatose