尝试锁定对象时的Try /catch
本文关键字:Try catch 锁定 对象 | 更新日期: 2023-09-27 18:18:46
我是多线程新手。我试图锁定对象时,它被另一个线程锁定,我期待一个错误,并尝试使用异常,但它没有工作。
class Program
{
static readonly object lockNum = new object();
static int A = 10;
public static void Thread1()
{
lock (lockNum)
{
A = 100;
Console.WriteLine(A);
}
}
public static void Thread2()
{
Thread.Sleep(1000);
lock (lockNum)
{
Thread.Sleep(9000);
Console.WriteLine(A);
Console.WriteLine("Thread 2 is executed");
}
}
public static void Thread3()
{
Thread.Sleep(3000);
try
{
lock (lockNum)
{
Console.WriteLine(A);
Console.WriteLine("Thread 3 is executed");
}
}
catch (Exception ex)
{
Console.WriteLine("Object is locked");
}
}
}
public class MyClass
{
public static void Main()
{
Thread tid1 = new Thread(new ThreadStart(Program.Thread1));
Thread tid2 = new Thread(new ThreadStart(Program.Thread2));
Thread tid3 = new Thread(new ThreadStart(Program.Thread3));
tid1.Start();
tid2.Start();
tid3.Start();
Console.ReadLine();
}
}
Thread2和Thread3在Thread.Sleep(9000);
i之后一起运行,预计在3秒后会出现异常,因为对象仍然被Thread2锁定。我试图使Thread3睡眠3秒再次检查对象是否被解锁(也许WriteLine错误),并重复,直到对象被解锁。
锁不会抛出异常,它们只是等待,直到其他线程释放了锁。
如果希望在无法声明lock
时跳过代码,可以使用
if (Monitor.TryEnter(lockNum))
{
Console.WriteLine("No one else had the lock, now it's mine!");
}
else
{
Console.WriteLine("Another thread won :(");
}
您可以选择为该方法提供超时
你的代码应该是这样的:
public static void Thread3()
{
Thread.Sleep(3000);
try
{
if (Monitor.TryEnter(lockNum))
{
Console.WriteLine(A);
Console.WriteLine("Thread 3 is executed");
}
else throw new Exception();
}
catch (Exception ex)
{
Console.WriteLine("Object is locked");
}
}
EDIT1:啊……解释是由另一个人提供的,
实际上这不是最好的处理方式。异常非常多。您可以摆脱try catch块,而不是抛出异常,您可以打印出您的消息