gpt4 book ai didi

c# - 使用对象而不是 this 获取锁 - 线程

转载 作者:行者123 更新时间:2023-11-30 16:14:49 24 4
gpt4 key购买 nike

<分区>

我正在尝试学习 C# 中的线程,我在几篇文章中看到了一些突然出现的东西,但我不确定我是否完全理解它:在给定的两个示例中,锁定“this”与“thisLock”之间的根本区别是什么。

示例 1:

class Account
{
decimal balance;
private Object thisLock = new Object();

public void Withdraw(decimal amount)
{
lock (thisLock)
{
if (amount > balance)
{
throw new Exception("Insufficient funds");
}
balance -= amount;
}
}
}

示例 2:

class Account
{
decimal balance;

public void Withdraw(decimal amount)
{
lock (this)
{
if (amount > balance)
{
throw new Exception("Insufficient funds");
}
balance -= amount;
}
}
}

根据我的理解,我会认为“thisLock”只会阻止其他线程进入该特定代码区域。

锁定“this”是否会停止对该对象的所有操作,即其他线程对其他方法的调用?

我是否从根本上没有理解这一点,或者这是正确的结论吗?

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