In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the relevant knowledge of "thread and task case analysis in C#". The editor shows you the operation process through the actual case, and the operation method is simple, fast and practical. I hope this article "Thread and Task instance Analysis in C#" can help you solve the problem.
Thread
Threads: it takes time for all waiting operations, such as moving files, database, and network access, to start a new thread and complete other tasks at the same time. Multiple threads of a process can run on different CPU or different kernels of multicore CPU at the same time.
When an application starts, it starts a process (the carrier of the application), and then the process starts multiple threads.
First, use the Thread class to start threads and data transfer
The Thread class allows you to create and control threads, and the Thread constructor is a delegate type with no parameters and no return value.
1 ️ThreadStart passes a method with no parameter and no return type to Thread-ThreadStart.
Public delegate void ThreadStart ()
Example:
Static void test () {Console.WriteLine ("test is start"); Console.WriteLine ("test is running"); Thread.Sleep (3000); Console.WriteLine ("test is completed");} static void Main (string [] args) {Thread th = new Thread (test); th.Start () Console.WriteLine ("main is completed");}
2 ️expressions pass in an anonymous method (or lambda expression) to Thread. Cases where the code of the incoming method is simple
Static void Main (string [] args) {/ / lambad expression Thread th = new Thread (() = > {Console.WriteLine ("child thread 1-ID:" + Thread.CurrentThread.ManagedThreadId);}); th.Start () / Anonymous method Thread th3 = new Thread (delegate () {Console.WriteLine ("child thread 2-ID:" + Thread.CurrentThread.ManagedThreadId);}); th3.Start (); Console.WriteLine ("main is completed");}
3 ️argument passes a parameter method-ParameterizedThreadStart with no return value to Thread. This parameter can only be of type object and can have only one parameter.
Public delegate void ParameterizedThreadStart (object? Obj)
Example:
Static void download (object o) {string str = o as string; Console.WriteLine ("address:" + str);} static void Main (string [] args) {Thread th = new Thread (download); th.Start ("http://baidu.com"); Console.WriteLine (" main is completed ");}
Note: a successful cast with as will output correctly, and a failure will output null.
The above data transmission methods are based on static variables, but defining too many static variables will cause multiple threads to access the same static variable, resulting in resource conflicts.
Although static variables are easy to access, static variables are generally public and easy to be confused.
4 ️arguments passes a method with multiple parameters without a return value to Thread (defining a structure), but cannot be cast with as.
Public struct data {public string message; public int age;} static void download (object o) {data str = (data) OTAC / cast Console.WriteLine ("Information:" + str.message); Console.WriteLine ("Age:" + str.age) } static void Main (string [] args) {data da = new data (); da.message = "sss"; da.age = 3; Thread th = new Thread (download); th.Start (da); Console.WriteLine ("main is completed");}
Because the structure is a value type and cannot be null, you cannot cast it with as.
5 ️clients passes data through a custom class (about to call a member method of a class through a thread)
First create a download class:
Class downLoad {public string URL {get; private set;} public string Message {get; private set;} / / Constructor public downLoad (string uRL, string message) {URL = uRL; Message = message } / / download method public void load () {Console.WriteLine ("get information from" + URL + ":" + Message);}} "
Pass the member methods of this class into Thread in the main program:
Static void Main (string [] args) {var download = new downLoad ("www.baidu.com", "mp4"); Thread th = new Thread (download.load); th.Start (); Console.WriteLine ("main is completed"); Console.ReadKey ();}
? Knowledge expansion 1-foreground thread and background thread:
The process of the application needs to wait for all foreground threads to complete its task before it ends. The background thread shuts down automatically after the application is closed, even if the background thread has not finished executing. By default, threads created with the Thread class are foreground threads and threads in the thread pool are background threads. When the Thread class creates a thread, you can set the IsBackground property to indicate whether it is a background thread.
? Knowledge extension 2-priority of threads
A thread has an operating system schedule, and a CPU can only do one thing at a time (running a computing task in a thread). When there are many threads that need CPU execution, the thread scheduler will determine which thread to execute first according to the thread's priority. If the priority is the same, a round robin rule is used to execute each thread one by one.
In the Thread class, you can set the Priority property to affect the basic priority of the thread, the Priority property is a value defined by the ThreadPriority enumeration, and the definition levels are Highest,AboveNormal,Normal,BelowNormal and Lowest.
Therefore, for important thread tasks, you can set the thread priority a little higher so that it can be executed as soon as possible.
If you need to wait for the code that follows the execution of the thread, you can call the join method of the Thread object, which joins the thread and stops the current thread until the joined thread finishes executing.
Second, thread pool ThreadPool class
Since thread creation takes time, if you have different small tasks to complete, you can create multiple threads in advance. The system has a ThreadPool class to manage threads, which increases the number of threads when they are needed and decreases when they are not needed. The maximum number of threads in the pool is configurable. In dual-core CPU, the default settings are 1023 worker threads and 1000 IO threads, and if more threads are needed (exceeding the maximum number of thread pools), the latest tasks need to be queued.
The thread pool is used, that is, the ThreadPool.QueueUserWorkItem method is called, which requires passing in a delegate of type WaitCallBack (that is, a method with an object parameter). ThreadPool then finds an idle thread in the pool to execute the incoming method.
Static void Main (string [] args) {for (int I = 0; I < 10; iTunes +) {ThreadPool.QueueUserWorkItem (work);} Thread.Sleep (10000);} static void work (object state) {Console.WriteLine ("thread id" + Thread.CurrentThread.ManagedThreadId);}
It is important to note that:
All the threads in the thread pool are background threads, and if all the foreground threads in the process end, all background threads will follow. The background thread that enters the pool cannot be changed to the foreground thread. You cannot set a priority or name for a thread that enters the pool. Threads that enter the pool can only be used for short-time tasks. If the thread is to run all the time, apply the Thread class to create a thread.
Task
A task indicates that the work of a unit should be completed, which can be run in a separate thread or start a task synchronously. Tasks are managed in the background using ThreadPool, which means that tasks are also started by background threads.
One, create and start the task
There are two ways to start a task:
Static void Main (string [] args) {/ / first: use TaskFactory TaskFactory tf = new TaskFactory (); tf.StartNew (work); / / second: use Task Task t = new Task (work); t.Start (); Console.WriteLine ("main is completed") } static void work () {Console.WriteLine ("thread id" + Thread.CurrentThread.ManagedThreadId);}
It is important to note that when you use TaskFactory to create a task, the methods passed in are nonparametric.
Second, continuous tasks
If the execution of one task T1 depends on another task T2, then the execution of T1 needs to be started after the T2 execution is complete. (for example, after the Thunderbolt download is completed, the pop-up interface prompts) We can use continuous task ContinueWith at this time.
Static void Main (string [] args) {Task T1 = new Task (download); Task T2 = t1.ContinueWith (show); t1.Start (); Thread.Sleep (2000);} static void download () {Console.WriteLine ("downloading.") ; Thread.Sleep (1000);} static void show (Task t) {Console.WriteLine ("download complete!") ;}
It is important to note that the parameter of the method passed in T2 should be of type Task.
Third, the problem of resource conflict
In multithreading, if multiple threads access the same resource at the same time, the problem of resource conflict will arise. At this point, you need to lock the program with lock.
? What is a resource conflict?
Class state {public int num= 5; public void checknum () {if (num==5) {num++; Console.WriteLine ("value of num:" + num+ "current thread id:" + Thread.CurrentThread.ManagedThreadId);} num= 5 }} static void Main (string [] args) {state st = new state (); for (int I = 0; I < 10; iTunes +) {Thread th = new Thread (st.checknum); th.Start ();}}
When the main program uses multithreading to call the check method of the state class, you can see that num=5 and num=6 cause resource conflicts.
? Lock objects accessed by multiple threads
Object _ lock = new object (); public int num= 5; public void checknum () {lock (_ lock) {if (num==5) {num++; Console.WriteLine ("value of num:" + num+ "current thread id:" + Thread.CurrentThread.ManagedThreadId);} num= 5 }}
This is the end of the content of "Thread and Task instance Analysis in C#". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.