Why do you give up using Thread. Sleep and thread. sleep?

Source: Internet
Author: User

Why do you give up using Thread. Sleep and thread. sleep?
Preface

This article does not mean to abandon Thread. Sleep completely, but to describe the conditions for use!

Scenario

In many cases, we need a scheduled service to process the business.

However, instead of executing the task every N minutes, you can calculate the next processing time point after processing the task.

When this time point is reached, the trigger program starts to execute the code again.

 

Common Practice

  

In general, while (true) {Thread. Sleep ()} is used for implementation. If you are not talking nonsense, check the code version 1:

Class Program {static void Main (string [] args) {var workLists = new List <string> () {"Task 1", "Task 2", "Task 3 ", "task 4"}; foreach (var task in workLists) {var thread = new System. threading. thread (new System. threading. parameterizedThreadStart (Work. doWork); thread. start (task );}}}

 

Class Work {public static void DoWork (object target) {var taskType = target as string; var interval = 1*60*1000; // processing failed, retry var maxTimes = 5 in 1 minute; var retryTimes = 0; while (true) {while (retryTimes <maxTimes) {var OK = Proccess (taskType); if (OK) {retryTimes = maxTimes;} else {retryTimes ++; System. threading. thread. sleep (interval) ;}} var tim = GetTotalMillisecondsForNext (); // calculate the time from the next start of processing System. threading. thread. sleep (tim); // after a period of suspension, wake up retryTimes = 0 ;}} private static bool Proccess (string taskType) {Console. writeLine ("Start processing: {0}", taskType); return true;} private static int GetTotalMillisecondsForNext () {// here, return 2*1000 is determined based on your own business ;}}

The code is easy to understand.

 

Analysis

In version 1, the Thread is forcibly created in a loop, and the System. Threading. Thread. Sleep (tim) is used to suspend the Thread and then wake up again.

This method is a waste of system thread resources. It's like taking a trap! Threads are a very valuable resource. Creation, destruction, and switching all consume quite a lot of performance.

When Sleep is used, it means: I don't need it now, but you don't want to use it either. You want to use it? Create one by yourself.

Some people say that Sleep does not occupy CPU! Yes, it does not occupy the CPU, but occupies the thread resources, which hinders the system's thread scheduling!

Refer to this article

Threads are a limited resource, they take approximately 200,000 cycles to create and about 100,000 cycles to destroy. by default they reserve 1 megabyte of virtual memory for its stack and use 2,000-8,000 cycles for each context switch.This makes any waiting threadHugeWaste.

 

Improvement

Use System. Timers. Timer to improve our program. When executing the code that processes the business, stop timer first. After the processing is completed, calculate the execution time point, assign it to timer and start it. Check the code version 2.

Class Program {static void Main (string [] args) {var workLists = new List <string> () {"Task 1", "Task 2", "Task 3 ", "Task 4"}; Parallel. forEach (workLists, new ParallelOptions () {MaxDegreeOfParallelism = 3}, (task) =>{ new Work2 () {TaskType = task }. doWork () ;}); Console. readLine ();}}
Class Work2 {private Timer _ workTimer; public string TaskType {get; set;} public void DoWork () {_ workTimer = new System. timers. timer (); _ workTimer. interval = 1000; _ workTimer. elapsed + = new ElapsedEventHandler (TimerHanlder); _ workTimer. start ();} private void TimerHanlder (object sender, ElapsedEventArgs e) {_ workTimer. stop (); var interval = 1*60*1000; // processing failed. Retry var maxTimes = 5 in 1 minute; var retryTimes = 0; while (retryTimes <maxTimes) {var OK = Proccess (); if (OK) {retryTimes = maxTimes;} else {retryTimes ++; System. threading. thread. sleep (interval) ;}} var times = GetTotalSecondsForNext (); Console. writeLine ("{0} seconds later", times); _ workTimer. interval = times * 1000; // calculate the time from the next Processing start _ workTimer. start ();} private bool Proccess () {Console. writeLine ("Start processing: {0}", TaskType); return true;} private int GetTotalSecondsForNext () {// return 3 is determined based on your own business ;}}

Note: The Console. ReadLine (); in the Main method is very important. It puts the Main thread in the waiting state and the Child thread can be executed continuously without interruption.

Summary

1: Use Task instead of new System. Threading. Thread. Whether to create threads should be determined by the system and reusable resources should be used

2: System. Threading. Thread. Sleep (interval); applicable only to "Limited" loop scenarios, such as retrying up to N times, countdown, etc.

 

 

If this is not the case, make sure that you are correct!

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.