search
HomeBackend DevelopmentC#.Net TutorialShare how C# ensures thread safety under multi-threading

Multi-threadingProgramming Compared with single-threading, there will be a unique problem, which is the issue of thread safety. The so-called thread safety means that if there are multiple threads running at the same time in the process where your code is located, these threads may run this code at the same time. If the results of each run are the same as those of single-threaded runs, and the values ​​of other variables are also the same as expected. Thread safety issues are caused by global variables and static variables.

In order to ensure the security of accessing static variables in multi-threaded situations, a lock mechanism can be used to ensure it, as shown below:

//Static global variables that need to be locked

 private static bool _isOK = false;
        //lock只能锁定一个引用类型变量
        private static object _lock = new object();
        static void MLock()
        {
            //多线程
            new System.Threading.Thread(Done).Start();
            new System.Threading.Thread(Done).Start();
            Console.ReadLine();
        }
        static void Done()
        {
            //lock只能锁定一个引用类型变量
            lock (_lock)
            {
                if (!_isOK)
                {
                    Console.WriteLine("OK");
                    _isOK = true;
                }
            }
        }

It should be noted that Lock can only lock an object of reference type. In addition, in addition to the lock mechanism, higher versions of C# have added async and await methods to ensure thread safety, as shown below:

public static class AsynAndAwait
{
        //step 1 
        private static int count = 0;
        //用async和await保证多线程下静态变量count安全
        public async static void M1()
        {
            //async and await将多个线程进行串行处理
            //等到await之后的语句执行完成后
            //才执行本线程的其他语句
            //step 2
            await Task.Run(new Action(M2));
            Console.WriteLine("Current Thread ID is {0}", System.Threading.Thread.CurrentThread.ManagedThreadId);
            //step 6
            count++;
            //step 7
            Console.WriteLine("M1 Step is {0}", count);
        }
        public static void M2()
        {
            Console.WriteLine("Current Thread ID is {0}", System.Threading.Thread.CurrentThread.ManagedThreadId);
            //step 3
            System.Threading.Thread.Sleep(3000);
            //step 4
            count++;
            //step 5
            Console.WriteLine("M2 Step is {0}", count);
        }
}

In the timing diagram, we can know that there are two Threads interact, as shown in the figure below:

Share how C# ensures thread safety under multi-threading

After using async and await, the execution sequence of the above code is as shown in the figure below:

Share how C# ensures thread safety under multi-threading

If there are only read operations for global variables and static variables in each thread, but no write operations, generally speaking, this global variable is thread-safe; if multiple threads read a variable at the same time Write operations generally need to consider thread synchronization, otherwise thread safety may be affected

The above is the detailed content of Share how C# ensures thread safety under multi-threading. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C# .NET Ecosystem: Frameworks, Libraries, and ToolsC# .NET Ecosystem: Frameworks, Libraries, and ToolsApr 24, 2025 am 12:02 AM

The C#.NET ecosystem provides rich frameworks and libraries to help developers build applications efficiently. 1.ASP.NETCore is used to build high-performance web applications, 2.EntityFrameworkCore is used for database operations. By understanding the use and best practices of these tools, developers can improve the quality and performance of their applications.

Deploying C# .NET Applications to Azure/AWS: A Step-by-Step GuideDeploying C# .NET Applications to Azure/AWS: A Step-by-Step GuideApr 23, 2025 am 12:06 AM

How to deploy a C# .NET app to Azure or AWS? The answer is to use AzureAppService and AWSElasticBeanstalk. 1. On Azure, automate deployment using AzureAppService and AzurePipelines. 2. On AWS, use Amazon ElasticBeanstalk and AWSLambda to implement deployment and serverless compute.

C# .NET: An Introduction to the Powerful Programming LanguageC# .NET: An Introduction to the Powerful Programming LanguageApr 22, 2025 am 12:04 AM

The combination of C# and .NET provides developers with a powerful programming environment. 1) C# supports polymorphism and asynchronous programming, 2) .NET provides cross-platform capabilities and concurrent processing mechanisms, which makes them widely used in desktop, web and mobile application development.

.NET Framework vs. C#: Decoding the Terminology.NET Framework vs. C#: Decoding the TerminologyApr 21, 2025 am 12:05 AM

.NETFramework is a software framework, and C# is a programming language. 1..NETFramework provides libraries and services, supporting desktop, web and mobile application development. 2.C# is designed for .NETFramework and supports modern programming functions. 3..NETFramework manages code execution through CLR, and the C# code is compiled into IL and runs by CLR. 4. Use .NETFramework to quickly develop applications, and C# provides advanced functions such as LINQ. 5. Common errors include type conversion and asynchronous programming deadlocks. VisualStudio tools are required for debugging.

Demystifying C# .NET: An Overview for BeginnersDemystifying C# .NET: An Overview for BeginnersApr 20, 2025 am 12:11 AM

C# is a modern, object-oriented programming language developed by Microsoft, and .NET is a development framework provided by Microsoft. C# combines the performance of C and the simplicity of Java, and is suitable for building various applications. The .NET framework supports multiple languages, provides garbage collection mechanisms, and simplifies memory management.

C# and the .NET Runtime: How They Work TogetherC# and the .NET Runtime: How They Work TogetherApr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)