Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use mutex Mutex in C # multithreading

Shulou Source: shulou.com Published: 2022-05-31 20:44:02 10月31日 Update

This article mainly explains "how to use mutex Mutex in C# multithreading". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn how to use the mutex Mutex in C# multithreading.

I. brief introduction

The outstanding feature of Mutex is that it can access resources exclusively across application domain boundaries, that is, it can be used to synchronize threads in different processes, of course, at the expense of more system resources.

Two main commonly used methods:

Public virtual bool WaitOne () blocks the current thread until the current System.Threading.WaitHandle receives a signal to acquire the mutex.

Public void ReleaseMutex () releases System.Threading.Mutex once.

II. Code

Case 1:

Class Program {private static Mutex mutex = new Mutex (); static void Main (string [] args) {Thread [] thread = new Thread [3]; for (int I = 0; I < 3; iTunes +) {thread [I] = new Thread (ThreadMethod1) / / method reference thread [I] .Name = "Thread-" + (iReader 1). ToString ();} for (int I = 0; I < 3; iThread +) {thread [I] .start ();} Console.ReadKey () } public static void ThreadMethod1 (object val) {mutex.WaitOne (); / / acquire lock for (int I = 1; I

Tags: Threads caching methods content more cases results resources learning running different practical deeper two cost code signals interests functions practicality Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Shulou Information NVidia Microsoft Apple