Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# Thread Safe Deep Copy

I have been reading alot of the other questions as well as alot of google searches and I've been unable to find a clear solution.

Based on some best practices I've read, the static methods of a class should be created thread safe, and the instance members should leave thread safety to the consumers.

I would like to implement a deep copy method for the class. The class itself has other reference type members. Is there any way to make the deep copy method thread safe without having to impose the overhead on all of the instanced members of the class?

like image 850
Sait Avatar asked May 19 '11 01:05

Sait


1 Answers

As to the cloning, stack overflow already has a good answer.

Deep cloning objects

as for thread safety, I would imagine the only guarantee is if you put locks around your member variables during your copy.

Update:

Ok, I've done some research. I think the most elegant way to ensure the thread safety of your members is for the calling threads to hold locks on the object instead of trying to implement it inside your class. Also, implement the ICloneable interface and then you can just do a binary copy of the entire object easily. See the answer in the link I posted above. Of course, you could still implement locks for your static members inside your class easily.

like image 93
Jonathan Henson Avatar answered Oct 11 '22 03:10

Jonathan Henson