C# Task 线程锁
时间: 2023-10-01 07:10:06 浏览: 175
在 C# 中,可以使用锁机制来实现线程同步。锁机制是一种互斥机制,它确保在任何给定时间内,只有一个线程可以访问被锁定的代码块。
下面是使用锁的示例代码:
```csharp
class Program
{
private static object _lock = new object();
private static int _counter = 0;
static void Main(string[] args)
{
// 创建多个线程并启动
for (int i = 0; i < 5; i++)
{
Thread thread = new Thread(IncrementCounter);
thread.Start();
}
Console.ReadKey();
}
static void IncrementCounter()
{
lock (_lock) // 使用锁来确保只有一个线程能够进入临界区
{
_counter++;
Console.WriteLine($"Counter: {_counter}");
}
}
}
```
在上面的示例中,我们定义了一个静态对象 `_lock` 作为互斥锁,并且定义了一个静态变量 `_counter` 作为共享资源。在 `IncrementCounter` 方法中,我们使用 `lock` 语句来锁定 `_lock` 对象,确保只有一个线程能够进入临界区,对 `_counter` 进行递增操作。
这样,在多个线程同时调用 `IncrementCounter` 方法时,每次只有一个线程能够成功获取锁并执行临界区的代码,从而保证了对 `_counter` 的安全访问。
注意:锁的使用需要谨慎,不当的锁使用可能导致死锁等问题。在设计多线程应用程序时,请确保正确地使用锁以避免潜在的问题。
阅读全文
相关推荐


















