In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article "C# multithreaded programming Task how to use" most people do not understand, so the editor summed up the following content, detailed, clear steps, with a certain reference value, I hope you can get something after reading this article, let's take a look at this "C# multithreaded programming Task how to use" article.
Basic Concepts Task advantages
ThreadPool has many advantages over Thread, but ThreadPool has some inconvenience, such as:
ThreadPool does not support interactive operations such as thread cancellation, completion, failure notification, etc.
ThreadPool does not support the priority of thread execution
The .NET Framework provided a more powerful concept in 4. 0: Task. Task optimizes on top of ThreadPool and provides more API. Take a look at a simple example:
Using System;using System.Threading;using System.Threading.Tasks;namespace TaskDemo {class Program {static void Main (string [] args) {/ / create Task Task t = new Task (() = > {Console.WriteLine ("Task starts working."); Thread.Sleep (5000);}) / / start t.Start (); t.ContinueWith ((task) = > {Console.WriteLine ("the status when the task is completed is:"); Console.WriteLine ("IsCanceled= {0}\ tIsCompleted= {1}\ tIsFaulted= {2}", task.IsCanceled, task.IsCompleted, task.IsFaulted);}) Console.WriteLine ("start"); Console.ReadKey ();} II. Use of Task to create a task
Tasks created by Task can be divided into two types: return values and no return values.
1. Use Task to create no return value
First take a look at the definition of Task:
You can see that the argument to the Task constructor is the Action delegate. So the code to create a task using Task is as follows:
Using System;using System.Threading;using System.Threading.Tasks;namespace TaskDemo {class Program {static void Main (string [] args) {# region 1, create a task using Task Task task = new Task (() = > TaskMethod ("Task 1")); Console.WriteLine ("before start status:" + task.Status) / / the task created by Task must call the start method to start task.Start (); Console.WriteLine ("after start status:" + task.Status); # endregion Console.ReadKey ();} static void TaskMethod (string name) {Console.WriteLine ("Task {0} is running on a thread id {1}. Is thread pool thread: {2} ", name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);}
The result of running the program:
Note: the status of the task, before Start is Created,Start, followed by WaitingToRun.
2. Use the Task.Run method to create a task
Tasks created by Task.Run can be started:
Using System;using System.Threading;using System.Threading.Tasks;namespace TaskDemo {class Program {static void Main (string [] args) {# region 1, create a task using Task / / Task task = new Task (() = > TaskMethod ("Task 1")); / / Console.WriteLine ("before start status:" + task.Status) / the task created by Task must call the start method to start / / task.Start (); / / Console.WriteLine ("after start status:" + task.Status); # endregion # region 2, create the task using Task.Run Task.Run (() = > TaskMethod ("Task Run")) # endregion Console.ReadKey ();} static void TaskMethod (string name) {Console.WriteLine ("Task {0} is running on a thread id {1}. Is thread pool thread: {2} ", name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);}
The result of running the program:
3. Use Factory to create a task using System;using System.Threading;using System.Threading.Tasks;namespace TaskDemo {class Program {static void Main (string [] args) {# region 1, create a task using Task / / Task task = new Task (() = > TaskMethod ("Task 1")); / / Console.WriteLine ("before start status:" + task.Status) / A task created by Task must call the start method to start / / task.Start (); / / Console.WriteLine ("after start status:" + task.Status); # endregion # region 2, create a task using Task.Run / / Task.Run (() = > TaskMethod ("Task Run")) # endregion # region 3. Create a task using Factory / / create a Task.Factory.StartNew using Task.Factory (() = > TaskMethod ("Task 4")); / / mark a long-running task, then the task will not use a thread pool and will run in a separate thread. Task.Factory.StartNew (() = > TaskMethod ("Task 5"), TaskCreationOptions.LongRunning); / / instantiate the TaskFactory object and then create TaskFactory factory = new TaskFactory (); factory.StartNew () = > TaskMethod ("Task 6"); # endregion Console.ReadKey () } static void TaskMethod (string name) {Console.WriteLine ("Task {0} is running on a thread id {1}. Is thread pool thread: {2} ", name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);}
The result of running the program:
4. Create a Task with a return value
The code is as follows:
Using System;using System.Threading;using System.Threading.Tasks;namespace TaskDemo {class Program {static void Main (string [] args) {# region 1, create a task using Task / / Task task = new Task (() = > TaskMethod ("Task 1")); / / Console.WriteLine ("before start status:" + task.Status) / A task created by Task must call the start method to start / / task.Start (); / / Console.WriteLine ("after start status:" + task.Status); # endregion # region 2, create a task using Task.Run / / Task.Run (() = > TaskMethod ("Task Run")) # endregion # region 3. Use Task.Factory to create a task / / Task.Factory.StartNew (() = > TaskMethod ("Task 4")); / marked as a long-running task, the task will not use the thread pool and will run in a separate thread. / / Task.Factory.StartNew (() = > TaskMethod ("Task 5"), TaskCreationOptions.LongRunning); # endregion # region 4, create a task with a return value TaskMethodReturn ("Main Thread Task"); / / create a Task Task task = CreateTask with a return value ("Task 1"); / / start task.Start () / / get the return value int result1 = task.Result; Console.WriteLine ($"Task 1 Result is: {result1}"); Task task2 = new Task (() = > TaskMethodReturn ("Task 2")); task2.Start (); int result2 = task2.Result; Console.WriteLine ($"Task 2 Result is: {result2}") Int result3= Task.Run (() = > TaskMethodReturn ("Task 3")) .result; Console.WriteLine ($"Task 3 Result is: {result3}"); int result4 = Task.Factory.StartNew (() = > TaskMethodReturn ("Task 4")) .Result; Console.WriteLine ($"Task 4 Result is: {result4}"); # endregion Console.ReadKey () } / return a Task / static Task CreateTask (string name) {/ / parameter is Func return new Task (() = > TaskMethodReturn (name) } static void TaskMethod (string name) {Console.WriteLine ("Task {0} is running on a thread id {1}. Is thread pool thread: {2} ", name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);} static int TaskMethodReturn (string name) {Console.WriteLine (" Task {0} is running on a thread id {1}. Is thread pool thread: {2} ", name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread); Thread.Sleep (TimeSpan.FromSeconds (2)); return 42;}
The result of running the program:
We said at the beginning of the article that Task is based on ThreadPool, so how to prove it? Look at the following code:
/ the thread testing Task comes from ThreadPool/// static void Test () {/ / sets the maximum number of threads in the thread pool ThreadPool.SetMaxThreads (6,6); / / creates a collection of Task List taskList = new List (); / / creates a collection of type int to hold the thread ID List threadIdList = new List () / / create 50 threads for using Task loop (int I = 0; I
< 30; i++) { int k = i; Task task = Task.Run(() =>{/ / the current thread ID is added to the collection threadIdList.Add (Thread.CurrentThread.ManagedThreadId); Console.WriteLine ($"this is {k} loop ThreadID: {Thread.CurrentThread.ManagedThreadId.ToString (" 00 ")}"); / / hibernating Thread.Sleep (200);}) / / add task to the collection taskList.Add (task);} / wait for all threads to finish executing Task.WaitAll (taskList.ToArray ()); / / output total number of Console.WriteLine ($"Total number of threads: {threadIdList.Distinct (). Count ()}");}
The result of running the program:
As you can see from the results, the threads in Task do come from ThreadPool.
III. Common methods
Let's use the following example to explain some of the more common methods in Task. Multiple developers work together to develop a project, and each person is responsible for the development of a module. We can think of this process as multithreading. The code is as follows:
Using System;using System.Collections.Generic;using System.Linq;using System.Threading;using System.Threading.Tasks;namespace TaskDemo {class Program {static void Main (string [] args) {# region 1, create a task using Task / / Task task = new Task (() = > TaskMethod ("Task 1")); / / Console.WriteLine ("before start status:" + task.Status) / A task created by Task must call the start method to start / / task.Start (); / / Console.WriteLine ("after start status:" + task.Status); # endregion # region 2, create a task using Task.Run / / Task.Run (() = > TaskMethod ("Task Run")) # endregion # region 3. Create a task using Factory / / create a task using Task.Factory (() = > TaskMethod ("Task 4")); / mark a long-running task, then the task will not use a thread pool and run in a separate thread. / / Task.Factory.StartNew (() = > TaskMethod ("Task 5"), TaskCreationOptions.LongRunning); / / instantiate the TaskFactory object and then create / / TaskFactory factory = new TaskFactory (); / / factory.StartNew (() = > TaskMethod ("Task 6")); # endregion # region 4, create a task with a return value / / TaskMethodReturn ("Main Thread Task") / create Task / / Task task = CreateTask ("Task 1") with return value; / / start / / task.Start (); / get the return value / / int result1 = task.Result; / / Console.WriteLine ($"Task 1 Result is: {result1}") / / Task task2 = new Task (() = > TaskMethodReturn ("Task 2")); / / task2.Start (); / / int result2 = task2.Result; / / Console.WriteLine ($"Task 2 Result is: {result2}"); / / int result3= Task.Run () = > TaskMethodReturn ("Task 3"). Result / / Console.WriteLine ($"Task 3 Result is: {result3}"); / / int result4 = Task.Factory.StartNew (() = > TaskMethodReturn ("Task 4")) .result; / / Console.WriteLine ($"Task 4 Result is: {result4}"); # endregion # region Test Task thread is from ThreadPool / / Test () # endregion / / Cooperative development project, each person is responsible for a module, which can be thought of as multithreaded Console.WriteLine ("start working on a big project!") ; Task.Run (() = > CodingShow ("Tom", "build micro-service architecture!")) ; Task.Run (() = > CodingShow ("Kevin", "Wechat interface!")) ; Task.Run (() = > CodingShow ("Jack", "build background framework!")) ; Task.Run (() = > CodingShow ("Alex", "Design database!")) ; Task.Run (() = > CodingShow ("Lee", "Alipay interface docking!") ; Console.ReadKey ();} / return a Task / static Task CreateTask (string name) {/ / parameter is Func return new Task (() = > TaskMethodReturn (name) } static void TaskMethod (string name) {Console.WriteLine ("Task {0} is running on a thread id {1}. Is thread pool thread: {2} ", name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);} static int TaskMethodReturn (string name) {Console.WriteLine (" Task {0} is running on a thread id {1}. Is thread pool thread: {2} ", name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread); Thread.Sleep (TimeSpan.FromSeconds (2)); return 42 } / the thread that tests Task comes from ThreadPool / static void Test () {/ / sets the maximum number of threads in the thread pool ThreadPool.SetMaxThreads (6,6); / / creates a collection of Task List taskList = new List () / / create a collection of type int to hold the thread ID List threadIdList = new List (); / / create 50 thread for (int I = 0; I) using the Task loop
< 30; i++) { int k = i; Task task = Task.Run(() =>{/ / the current thread ID is added to the collection threadIdList.Add (Thread.CurrentThread.ManagedThreadId); Console.WriteLine ($"this is {k} loop ThreadID: {Thread.CurrentThread.ManagedThreadId.ToString (" 00 ")}"); / / hibernating Thread.Sleep (200);}) / / add task to the collection taskList.Add (task);} / wait for all threads to finish executing Task.WaitAll (taskList.ToArray ()); / / output total number of Console.WriteLine ($"Total number of threads: {threadIdList.Distinct (). Count ()}") } / simulate the Coding process / static void CodingShow (string name, string projectName) {Console.WriteLine ($"CodingShow Start {name} {projectName} {Thread.CurrentThread.ManagedThreadId.ToString (" 00 ")}"); long lResult = 0 For (int I = 0; I
< 1_000_000_000; i++) { lResult += i; } Console.WriteLine($"CodingShow End {name} {projectName} {Thread.CurrentThread.ManagedThreadId.ToString("00")} "); } }} 程序运行结果: 这时需求发生了变化,所有的模块都开发完成以后,开始搭建测试环境,修改代码如下: // 合作开发项目,每个人负责一个模块,可以认为是多线程Console.WriteLine("开始合作开发一个大项目!");Task.Run(() => < 30; i++) { int k = i; Task task = Task.Run(() =>{/ / the current thread ID is added to the collection threadIdList.Add (Thread.CurrentThread.ManagedThreadId); Console.WriteLine ($"this is {k} loop ThreadID: {Thread.CurrentThread.ManagedThreadId.ToString (" 00 ")}"); / / hibernating Thread.Sleep (200);}) / / add task to the collection taskList.Add (task);} / wait for all threads to finish executing Task.WaitAll (taskList.ToArray ()); / / output total number of Console.WriteLine ($"Total number of threads: {threadIdList.Distinct (). Count ()}") } / simulate the Coding process / static void CodingShow (string name, string projectName) {Console.WriteLine ($"CodingShow Start {name} {projectName} {Thread.CurrentThread.ManagedThreadId.ToString (" 00 ")}"); long lResult = 0 For (int I = 0; I < 1000, 000, 000; I +) {lResult + = I;} Console.WriteLine ($"CodingShow End {name} {projectName} {Thread.CurrentThread.ManagedThreadId.ToString (" 00 ")}") } the above is about the content of this article on "how to use C# multithreaded programming Task". I believe we all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.
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.