gpt4 book ai didi

c# - 尝试锁定对象时尝试/捕获

转载 作者:太空宇宙 更新时间:2023-11-03 21:17:13 26 4
gpt4 key购买 nike

我是多线程的新手。当对象被另一个线程锁定时,我试图锁定对象,我预计会出现错误并尝试使用 Exception,但它没有用。

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); 之后一起运行,我预计 3 秒后会出现异常,因为该对象仍被 Thread2 锁定。我试图让 Thread3 再次 sleep 3 秒以检查对象是否已解锁(可能是 WriteLine 错误)并重复直到对象被解锁。

最佳答案

锁不会抛出异常,它们只是等待其他线程释放锁。

如果您在无法领取时跳过代码,您可以使用

if (Monitor.TryEnter(lockNum))
{
Console.WriteLine("No one else had the lock, now it's mine!");
}
else
{
Console.WriteLine("Another thread won :(");
}

您可以选择为该方法提供超时。

关于c# - 尝试锁定对象时尝试/捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33252127/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com