< p >
SqlCommand.Clone()
方法创建深层拷贝还是浅层拷贝?此外,同时从多个线程调用 Clone()
方法是否安全(创建一个命令,多个线程可以复制、设置参数值和执行)?
SqlCommand.Clone()
方法创建深层拷贝还是浅层拷贝?此外,同时从多个线程调用 Clone()
方法是否安全(创建一个命令,多个线程可以复制、设置参数值和执行)?
在多个线程中调用 Clone
不安全,因为 SqlCommand
类本身不是线程安全的类。在克隆之前必须加锁 (lock
)。
但是可以使用像 Reflector
这样的程序查看 SqlCommand.Clone()
方法,以下是实际代码:
public SqlCommand Clone()
{
SqlCommand command = new SqlCommand(this);
Bid.Trace("<sc.SqlCommand.Clone|API> %d#, clone=%d#\n", this.ObjectID, command.ObjectID);
return command;
}
internal static void Trace(string fmtPrintfW, int a1, int a2)
{
if (((modFlags & ApiGroup.Trace) != ApiGroup.Off) && (modID != NoData))
{
NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2);
}
}
[DllImport("System.Data.dll", EntryPoint="DllBidTraceCW", CallingConvention=CallingConvention.Cdecl, CharSet=CharSet.Unicode)]
internal static extern void Trace(IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, int a1, int a2);
private SqlCommand(SqlCommand from) : this()
{
this.CommandText = from.CommandText;
this.CommandTimeout = from.CommandTimeout;
this.CommandType = from.CommandType;
this.Connection = from.Connection;
this.DesignTimeVisible = from.DesignTimeVisible;
this.Transaction = from.Transaction;
this.UpdatedRowSource = from.UpdatedRowSource;
SqlParameterCollection parameters = this.Parameters;
foreach (object obj2 in from.Parameters)
{
parameters.Add((obj2 is ICloneable) ? (obj2 as ICloneable).Clone() : obj2);
}
}
Connection
,因此它是浅复制。SqlCommand.Clone
方法执行浅层复制。任何引用类型的属性在两个 SqlCommand 实例中表示相同的对象。因此,不是线程安全的。SqlCommand
而不是克隆它。