SqlCommand.Clone() 是否创建深复制或浅复制?
SqlCommand.Clone()
是否创建深复制或浅复制?另外,从多个线程并发调用 Clone() 是否安全(创建一个多个线程可以复制、设置参数值并执行的命令)?
Does SqlCommand.Clone()
create a deep copy or shallow copy? Also, is it safe to call Clone()
from multiple threads concurrently (create one command that multiple threads can copy, set parameter values, and execute)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从多个线程调用
Clone
并不安全,因为SqlCommand
类本身不是线程安全类。在克隆之前你应该lock
。但是你可以使用
Reflector
等程序查看SqlCommand.Clone()
方法,这里是实际的代码:您可以看到它创建了一个新实例并向其中添加了旧实例的所有属性,但它不会深度复制所有属性“例如
Connection
”,因此它是浅复制。It is not safe to call
Clone
from multiple threads because theSqlCommand
class itself is not a thread safe class. you shouldlock
before cloning..However you can look at the
SqlCommand.Clone()
method using programs likeReflector
, here is the actual code:You can see that it create a new instance and add to it all properties of the old one, but it does not deep copy all properties "like
Connection
for instance" and so it a shallow copy.SqlCommand.Clone
方法执行浅复制。任何属于引用类型的属性都将表示两个 SqlCommand 实例中的同一对象。所以,不是线程安全的。AFAIK,.NET 框架中的所有 Clone() (MemberwiseClone) 方法都是浅拷贝。
您尚未发布代码,但我建议创建一个新的
SqlCommand
而不是克隆。The
SqlCommand.Clone
method performs a shallow copy. Any properties that are a reference type will represent the same object in both SqlCommand instances. So, not thread safe.AFAIK, all Clone() (MemberwiseClone) methods in the .NET framework are shallow copies.
You haven't posted your code, but I would suggest creating a new
SqlCommand
rather than cloning.