问:C#中LOCK的用法

jhdxhj 2010-09-16 03:00:29
问:C#中LOCK的用法,能否搞个最简单的例子研究研究
...全文
2249 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
VCACC 2010-10-19
  • 打赏
  • 举报
回复
一起学习。。。
yr1202 2010-09-16
  • 打赏
  • 举报
回复
lock(this)
{
lock(this)
{
}
}
会怎么样?
zhangaijiang 2010-09-16
  • 打赏
  • 举报
回复
glest 2010-09-16
  • 打赏
  • 举报
回复
目的:解决线程同步访问共享资源的问题
使用大意:lock住一个全局变量,就相当于告诉别的线程,我在使用这个全局变量,请等待。当线程推出lock的作用域时,就释放了对全局变量的锁,其他等待的线程可以访问该资源了。
代码:

//定义共享资源
object obj=new object();

//线程函数
void threadFun()
{
lock(obj)
{
//安全的访问资源
}
}



sunzhiguolu 2010-09-16
  • 打赏
  • 举报
回复
学习了...
ShinNakoruru 2010-09-16
  • 打赏
  • 举报
回复
假设你做了一个页面,上面一按钮,按了按钮以后做以下处理:

在服务器上打开文本文件,读取其中第一行的数字,+1,再写入,关闭文件。

其实就是个计数器哈。

当点的人特别多的时候,就会有上一个人的文件操作还没完成,下一个人又要打开,就会出现文件共享权限错误。
这时你定义一个static object obj;
lock(obj)
执行文件操作

因obj是static,被锁后其他线程无法访问,就会等待解锁,就不会执行文件操作,也不会出错了。、

大概就这意思。
benyouyong 2010-09-16
  • 打赏
  • 举报
回复
锁定.独占对象
wuyq11 2010-09-16
  • 打赏
  • 举报
回复
锁住当前实例:lock(this)
锁住此类的所有实例:lock(typeof([Type]))
对字符串的锁,会锁定所有相同内容的字符串,建议可以用静态字符串代替
lock关键字比Monitor简洁,其实lock就是对Monitor的Enter和Exit的一个封装
lock是一种比较好用的简单的线程同步方式
public void Function()
{
object lockThis = new object();
lock (lockThis)
{
}
}
还可使用monitor,mutex,ReaderWriterLock
BoyceLyu 2010-09-16
  • 打赏
  • 举报
回复

using System;
using System.Threading;

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

Random r = new Random();

public Account(int initial)
{
balance = initial;
}

int Withdraw(int amount)
{

// This condition will never be true unless the lock statement
// is commented out:
if (balance < 0)
{
throw new Exception("Negative Balance");
}

// Comment out the next line to see the effect of leaving out
// the lock keyword:
lock(thisLock)
{
if (balance >= amount)
{
Console.WriteLine("Balance before Withdrawal : " + balance);
Console.WriteLine("Amount to Withdraw : -" + amount);
balance = balance - amount;
Console.WriteLine("Balance after Withdrawal : " + balance);
return amount;
}
else
{
return 0; // transaction rejected
}
}
}

public void DoTransactions()
{
for (int i = 0; i < 100; i++)
{
Withdraw(r.Next(1, 100));
}
}
}

class Test
{
static void Main()
{
Thread[] threads = new Thread[10];
Account acc = new Account(1000);
for (int i = 0; i < 10; i++)
{
Thread t = new Thread(new ThreadStart(acc.DoTransactions));
threads[i] = t;
}
for (int i = 0; i < 10; i++)
{
threads[i].Start();
}
}
}
MSDN
xupeihuagudulei 2010-09-16
  • 打赏
  • 举报
回复
lock 对象。
主要用于处理并发问题

110,565

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧