c#线程安全深度复制 [英] c# Thread Safe Deep Copy

查看:80
本文介绍了c#线程安全深度复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读很多其他问题以及很多Google搜索,但是我一直找不到清晰的解决方案.

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?

推荐答案

对于克隆,堆栈溢出已经有了很好的答案.

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

深度克隆对象

关于线程安全,我想唯一的保证就是在复制期间在成员变量周围加锁.

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

更新:

好的,我已经做了一些研究.我认为确保成员线程安全的最优雅的方法是,调用线程在对象上持有锁,而不是尝试在类中实现它.同样,实现ICloneable接口,然后您就可以轻松地对整个对象进行二进制复制.请参阅我上面发布的链接中的答案.当然,您仍然可以轻松地为类中的静态成员实现锁.

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.

这篇关于c#线程安全深度复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆