我正在使用 C# 锁来阻止代码执行。如果我们在 Lock 中使用动态字符串输入,它是行不通的。
public class ParameterClass
{
public string A = string.Empty;
public Int64 B = 0;
}
class Program
{
static void Main(string[] args)
{
ParameterClass parm = new ParameterClass { A = "Test", B = 1 };
Thread thread = new Thread(ThreadFun);
thread.Start(parm);
System.Threading.Thread.Sleep(2000);
parm = new ParameterClass { A = "Test", B = 1 };
ThreadFun(parm);
}
public static void ThreadFun(object para)
{
ParameterClass parameter = (ParameterClass)para;
lock (parameter.B.ToString())
{
Console.WriteLine(DateTime.Now);
System.Threading.Thread.Sleep(20000);
}
}
} …Run Code Online (Sandbox Code Playgroud)