Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

An example Analysis of the number of completed Thread in C #

2025-04-05 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains the "C # thread completion number example analysis". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought. Let's study and learn "C # thread completion number example analysis"!

Solve a problem

If the program needs to send 5 requests to an Web, there is a certain chance that the request will fail due to network fluctuations. If you fail, you need to try again.

The sample code is as follows:

Class Program {private static int count = 0; static void Main (string [] args) {for (int I = 0; I)

< 5; i++) new Thread(HttpRequest).Start(); // 创建线程 // 用于不断向另一个线程发送信号 while (count < 5) { Thread.Sleep(100); } Console.WriteLine("任务执行完毕"); } // 模拟网络请求 public static void HttpRequest() { Console.WriteLine("开始一个任务"); // 随机生成一个数,如果为偶数,则模拟请求失败 bool isSuccess = (new Random().Next(0, 10)) % 2 == 0; // ... ...模拟请求 HTTP Thread.Sleep(TimeSpan.FromSeconds(2)); // 请求失败则重试 if (!isSuccess) { Console.WriteLine($"请求失败,count={count}"); new Thread(() =>

{HttpRequest ();}) .Start (); return;} / / complete a task, + 1 Interlocked.Add (ref count,1); Console.WriteLine ($"complete task, count= {count}");}}

The code is terrible, but we can use the CountdownEvent class to modify it.

CountdownEvent class

Represents a synchronization primitive that is in a signaled state when the count becomes 00:00.

In other words, set a counter, after each thread is completed, will subtract 1, when the counter is 0, it means that all threads have completed the task.

Constructors and methods

The constructor of the CountdownEvent class is as follows:

The constructor indicates that CountdownEvent (Int32) initializes a new instance of the CountdownEvent class with the specified count.

Common methods of the CountdownEvent class are as follows:

The method indicates that AddCount () increments the current count of CountdownEvent by 1. AddCount (Int32) increases the current count of CountdownEvent by the specified value. Reset () resets CurrentCount to the value of InitialCount. Reset (Int32) resets the InitialCount property to the specified value. Signal () registers the signal with the CountdownEvent while decreasing the value of the CurrentCount. Signal (Int32) registers a plurality of signals with the CountdownEvent while reducing the value of the CurrentCount by a specified number. TryAddCount () an attempt to add a CurrentCount. TryAddCount (Int32) an attempt to increase the CurrentCount of the specified value. Wait () blocks the current thread until CountdownEvent is set. Wait (CancellationToken) blocks the current thread until CountdownEvent is set, while observing CancellationToken. Wait (Int32) blocks the current thread until CountdownEvent is set, while measuring the timeout using a 32-bit signed integer. Wait (Int32, CancellationToken) blocks the current thread until CountdownEvent is set, and measures the timeout using a 32-bit signed integer while observing the CancellationToken. Wait (TimeSpan) blocks the current thread until CountdownEvent is set, while measuring the timeout using TimeSpan. Wait (TimeSpan, CancellationToken) blocks the current thread until CountdownEvent is set, and uses TimeSpan to measure the timeout while observing CancellationToken.

There are a lot of API. It's all right. Let's learn about it.

Example

Let's write a scenario code, one has five things that need to be done, send five people to implement each.

.wait (); used in a thread that waits for others to complete the task before continuing to execute.

Signal (); is used in the worker thread to signal to the CountdownEvent object that the task has been completed, and then CountdownEvent.CurrentCount will subtract 1.

When the counter is 0, the blocked thread resumes execution.

The code example is as follows:

Class Program {/ / there are 5 things at hand: private static CountdownEvent countd = new CountdownEvent (5); static void Main (string [] args) {Console.WriteLine ("start the task"); / / ask five people at the same time to do 5 things for (int I = 0; I < 5) Thread thread +) {Thread thread = new Thread (DoOne); thread.Name = $"{I}"; thread.Start ();} / / wait for them to complete things countd.Wait (); Console.WriteLine ("task completed, thread exit"); Console.ReadKey () } public static void DoOne () {int n = new Random () .Next (0,10); / / Simulation takes n seconds to complete Thread.Sleep (TimeSpan.FromSeconds (n)); / / done, minus one thing countd.Signal () Console.WriteLine ($"{Thread.CurrentThread.Name} done one thing");}}

The example is simple: when each thread completes its own task, it needs to call the Signal () method to subtract 1 from the counter.

.wait (); you can wait for all tasks to be completed.

It is important to note that if Signal () is not called or if the counter has not been 0, then Wait () will wait indefinitely.

Of course, Wait () can set the wait time

In addition, we also see that the commonly used methods are AddCount (), Reset (), and so on.

The wait control of this class is relatively loose, and when it can be executed after Wait () depends on the consciousness of other threads.

If we find that the thread fails to execute the task, we can try again without calling Signal () or using AddCount () to increase the number of times

Thank you for reading, the above is the content of "C# thread completion example analysis". After the study of this article, I believe you have a deeper understanding of the problem of C# thread completion example analysis. The specific use of the situation also needs to be verified by practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report