C#同步

C#同步 首页 / C#入门教程 / C#同步

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

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

主要用于存取款等交易。

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();  
    }  
}  

输出:

无涯教程网

链接:https://www.learnfk.comhttps://www.learnfk.com/csharp/c-sharp-thread-synchronization.html

来源:LearnFk无涯教程网

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();  
    }  
}  

输出:

无涯教程网

链接:https://www.learnfk.comhttps://www.learnfk.com/csharp/c-sharp-thread-synchronization.html

来源:LearnFk无涯教程网

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

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

教程推荐

Serverless进阶实战课 -〔静远〕

React Native 新架构实战课 -〔蒋宏伟〕

React Hooks 核心原理与实战 -〔王沛〕

基于人因的用户体验设计课 -〔刘石〕

人人都用得上的写作课 -〔涵柏〕

用户体验设计实战课 -〔相辉〕

Redis核心技术与实战 -〔蒋德钧〕

网络编程实战 -〔盛延敏〕

从0开始做增长 -〔刘津〕

好记忆不如烂笔头。留下您的足迹吧 :)