无涯教程-C# - 同步

23 阅读2分钟

同步是一种只允许一个线程在特定时间访问资源的技术。在分配的线程完成其任务之前,任何其他线程都不能中断。

在多线程程序中,允许线程在所需的执行时间内访问任何资源。线程共享资源并异步执行。访问共享资源(数据)是一项关键任务,有时可能会导致系统停止。无涯教程通过使线程同步来处理它。

主要用于存取款等交易。

C# Lock锁

无涯教程可以使用C#lock关键字同步执行程序。用于获取当前线程的锁,执行任务,然后释放锁。它确保其他线程在执行结束之前不会中断执行。

在这里,将创建两个异步和同步执行的示例。

C#示例:没有同步

在本例中,没有使用锁。此示例异步执行。换句话说,线程之间存在上下文切换。

using System;  
using System.Threading;  
class Printer  
{  
    public void PrintTable()  
    {  
        for (int i = 1; i <= 10; i++)  
        {  
            Thread.Sleep(100);  
            Console.WriteLine(i);  
        }  
    }  
}  
class Program  
{  
    public static void Main(string[] args)  
    {  
        Printer p = new Printer();  
        Thread t1 = new Thread(new ThreadStart(p.PrintTable));  
        Thread t2 = new Thread(new ThreadStart(p.PrintTable));  
        t1.Start();  
        t2.Start();  
    }  
}  

输出:

1
1
2
2
3
3
4
4
5
5
6
6
7
7
8
8
9
9
10
10

C#线程同步示例

在本例中,无涯教程使用的是LOCK。此示例同步执行。换句话说,线程之间没有上下文切换。在输出部分中,可以看到第二个线程在第一线程完成其任务后开始工作。

using System;  
using System.Threading;  
class Printer  
{  
    public void PrintTable()  
    {  
        lock (this)  
        {  
            for (int i = 1; i <= 10; i++)  
            {  
                Thread.Sleep(100);  
                Console.WriteLine(i);  
            }  
        }  
    }  
}  
class Program  
{  
    public static void Main(string[] args)  
    {  
        Printer p = new Printer();  
        Thread t1 = new Thread(new ThreadStart(p.PrintTable));  
        Thread t2 = new Thread(new ThreadStart(p.PrintTable));  
        t1.Start();  
        t2.Start();  
    }  
}  

输出:

1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
6
7
8
9
10

参考链接

www.learnfk.com/csharp/c-sh…