C#之MethodImpl(MethodImplOptions.Synchronized)

[MethodImpl(MethodImplOptions.Synchronized)] 是 C# 中用于指定方法同步的一个特性,它控制方法的执行方式,确保在多线程环境下某个方法的执行是线程安全的。它可以用来避免多个线程同时访问一个共享资源而导致的竞态条件。

private static int count = 0;

//[MethodImpl(MethodImplOptions.Synchronized)]
public static void Increment()
{
    Thread.Sleep(100); // 模拟一些处理
    int temp = count;
    count = temp + 1;
    Console.WriteLine($"Current value:{count}");

}
static void Main(string[] args)
{
    Thread t1 = new Thread(Increment);
    Thread t2 = new Thread(Increment);
    Thread t3 = new Thread(Increment);
    Thread t4 = new Thread(Increment);
    t1.Start();
    t2.Start();
    t3.Start();
    t4.Start();
    t1.Join();
    t2.Join();
    t3.Join();
    t4.Join();
    Console.WriteLine("Done!");


加上这个特性后

private static int count = 0;

[MethodImpl(MethodImplOptions.Synchronized)]
public static void Increment()
{
    Thread.Sleep(100); // 模拟一些处理
    int temp = count;
    count = temp + 1;
    Console.WriteLine($"Current value:{count}");

}
static void Main(string[] args)
{
    Thread t1 = new Thread(Increment);
    Thread t2 = new Thread(Increment);
    Thread t3 = new Thread(Increment);
    Thread t4 = new Thread(Increment);
    t1.Start();
    t2.Start();
    t3.Start();
    t4.Start();
    t1.Join();
    t2.Join();
    t3.Join();
    t4.Join();

posted @ 2025-02-13 13:26  JohnYang819  阅读(25)  评论(0)    收藏  举报