温馨提示×

C#中如何实现线程同步

c#
小樊
83
2024-08-27 10:10:38
栏目: 编程语言

在C#中,可以使用多种方法来实现线程同步

  1. 使用lock关键字:

lock关键字可以确保一次只有一个线程访问代码块。当一个线程已经获得了锁时,其他线程必须等待直到锁被释放。

class Program
{
    private static readonly object _lockObject = new object();

    static void Main(string[] args)
    {
        Task task1 = Task.Run(() => Work());
        Task task2 = Task.Run(() => Work());

        Task.WaitAll(task1, task2);
    }

    static void Work()
    {
        lock (_lockObject)
        {
            // 同步代码
        }
    }
}
  1. 使用Monitor类:

Monitor类提供了一种显式的方式来实现线程同步。与lock关键字类似,Monitor类也使用对象作为锁。

class Program
{
    private static readonly object _lockObject = new object();

    static void Main(string[] args)
    {
        Task task1 = Task.Run(() => Work());
        Task task2 = Task.Run(() => Work());

        Task.WaitAll(task1, task2);
    }

    static void Work()
    {
        Monitor.Enter(_lockObject);
        try
        {
            // 同步代码
        }
        finally
        {
            Monitor.Exit(_lockObject);
        }
    }
}
  1. 使用SemaphoreSemaphoreSlim类:

SemaphoreSemaphoreSlim类可以限制同时访问特定代码段的线程数量。这对于限制资源访问(如数据库连接)非常有用。

class Program
{
    private static readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);

    static void Main(string[] args)
    {
        Task task1 = Task.Run(() => Work());
        Task task2 = Task.Run(() => Work());

        Task.WaitAll(task1, task2);
    }

    static async void Work()
    {
        await _semaphore.WaitAsync();
        try
        {
            // 同步代码
        }
        finally
        {
            _semaphore.Release();
        }
    }
}
  1. 使用并发集合:

C#提供了一些线程安全的集合,如ConcurrentDictionaryConcurrentQueue等。这些集合在内部实现了线程同步,因此可以在多线程环境中安全地使用。

class Program
{
    private static readonly ConcurrentDictionary<int, int> _concurrentDictionary = new ConcurrentDictionary<int, int>();

    static void Main(string[] args)
    {
        Task task1 = Task.Run(() => Work());
        Task task2 = Task.Run(() => Work());

        Task.WaitAll(task1, task2);
    }

    static void Work()
    {
        // 使用线程安全的并发集合
        _concurrentDictionary.TryAdd(1, 1);
    }
}

这些方法可以帮助你在C#中实现线程同步。选择哪种方法取决于你的需求和场景。

0