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 what is the difference between task and thread in c #. It has a certain reference value. Interested friends can refer to it. I hope you will gain a lot after reading this article. Let's take a look at it.
1. What is thread?
When we talk about multithreading, we think of thread and threadpool, which are asynchronous operations. Threadpool is actually a collection of thread and has many advantages, but when there are many tasks, the global queue will compete and consume resources. Thread defaults to the foreground thread, and the main program must wait for the thread to finish running before it closes, while threadpool does the opposite.
Summary: threadpool does perform better than thread, but neither has good api zone control, and if the thread execution is unresponsive, it has to wait for the end, thus giving birth to the task task.
two。 What is task?
Task is simply a task. What's the difference between that and thread? The implementation behind Task also uses thread pool threads, but its performance is better than ThreadPoll because it does not use the global queue of the thread pool, but the local queue, which reduces resource competition between threads. At the same time, Task provides rich API to manage threads and control. But compared with the former two kinds of memory consumption, Task depends on CPU for multi-core CPU performance far ahead of the two, the performance of single-core CPU is no different.
3. There are two modes for creating a task task:
1. Creation with factory is performed directly, creation with new is not performed, and must wait until start is started.
Public void test () {var testTask = new Task (() = > {Console.WriteLine ("task start");}); testTask.Start (); var factoryTeak = Task.Factory.StartNew (() = > {Console.WriteLine ("factory task start");});}
two。 Let's take a look at the life cycle of task.
Var testTask = new Task (() = > {Console.WriteLine ("task start"); System.Threading.Thread.Sleep (2000);}); Console.WriteLine (testTask.Status); testTask.Start (); Console.WriteLine (testTask.Status); Console.WriteLine (testTask.Status) TestTask.Wait (); Console.WriteLine (testTask.Status); Console.WriteLine (testTask.Status)
Output result:
Created
Task start
Running
Running
RanToCompletion
RanToCompletion
You can see that task does execute asynchronously, and wait has good control over task.
3. Here are a few ways to control task
Var testTask = new Task (() = > {Console.WriteLine ("task start"); System.Threading.Thread.Sleep (2000);}); testTask.Start (); testTask.Wait (); var testTask = new Task (() = > {Console.WriteLine ("task start")) System.Threading.Thread.Sleep (2000);}); testTask.Start (); var factoryTeak = Task.Factory.StartNew (() = > {Console.WriteLine ("factory task start");}); Task.WaitAll (testTask, factoryTeak); Console.WriteLine ("end") Var testTask = new Task (() = > {Console.WriteLine ("task start"); System.Threading.Thread.Sleep (2000);}); testTask.Start (); var factoryTeak = Task.Factory.StartNew (()) = > {Console.WriteLine ("factory task start") }); Task.WaitAny (testTask, factoryTeak); Console.WriteLine ("end")
Wait () waits for a single task, Task.waitall () waits for multiple task, and waitany () executes any task to continue execution.
Callback execution of 4.task
Var testTask = new Task (() = > {Console.WriteLine ("task start"); System.Threading.Thread.Sleep (2000);}); testTask.Start (); var resultTest = testTask.ContinueWith ((Task) = > {Console.WriteLine ("testTask end"); return "end";}) Console.WriteLine (resultTest.Result)
Cancellation of 5.task
First, create an instance of the token that cancels task, and cancel it directly without starting task:
Var tokenSource = new CancellationTokenSource (); / / create and cancel task instance var testTask = new Task (() = > {for (int I = 0; I)
< 6; i++) { System.Threading.Thread.Sleep(1000); } },tokenSource.Token); Console.WriteLine(testTask.Status); tokenSource.Token.Register(()=>{Console.WriteLine ("task is to cancel");}); tokenSource.Cancel (); Console.WriteLine (testTask.Status)
Output result:
Created
Task is to cancel
Canceled
What if task starts up and really cancels task?
Var tokenSource = new CancellationTokenSource (); / / create cancel task instance var testTask = new Task (()) = > {for (int I = 0; I {Console.WriteLine ("task is to cancel");}); tokenSource.Cancel (); Console.WriteLine (testTask.Status); for (int I = 0; I
< 10; i++) { System.Threading.Thread.Sleep(1000); Console.WriteLine(testTask.Status); } 输出结果: Created WaitingToRun task is to cancel Running Running Running Running Running Running RanToCompletion RanToCompletion RanToCompletion RanToCompletion RanToCompletion 可以看出其实并没有取消task,此时task还在继续跑。 6.task的嵌套 var parentTask = new Task(()=>{var childTask = new Task (() = > {System.Threading.Thread.Sleep (2000); Console.WriteLine ("childTask to start");}); childTask.Start (); Console.WriteLine ("parentTask to start");}); parentTask.Start () ParentTask.Wait (); Console.WriteLine ("end")
At this time, it is a normal association, and the parent task and child task have no effect.
Var parentTask = new Task (() = > {var childTask = new Task (() = > {System.Threading.Thread.Sleep (2000); Console.WriteLine ("childTask to start");}, TaskCreationOptions.AttachedToParent); childTask.Start (); Console.WriteLine ("parentTask to start");}) ParentTask.Start (); parentTask.Wait (); Console.WriteLine ("end")
At this point, there is an association between the parent task and the child task, and the wait will wait for the parent and son task to finish execution.
The problem of 6.task deadlock
We can set the maximum waiting time. If the waiting time is exceeded, we will no longer wait. Let's modify the code and set the maximum waiting time to 5 seconds (which can be set according to the actual situation in the project). If it exceeds 5 seconds, output which task went wrong.
7. The use of Spinlock
For example, Parallel.for and Parallel.foreach are not thread safe and may not meet your expectations. You need to add locks to solve this problem. We can add lock and spinlock (spin locks) to solve the problem.
SpinLock slock = new SpinLock (false); var testLock= new object (); long sum1 = 0; long sum2 = 0; long sum3 = 0; Parallel.For (0, 100000, I = > {sum1 + = I;}) Parallel.For (0, 100000, I = > {bool lockTaken = false; try {slock.Enter (ref lockTaken); sum2 + = I } finally {if (lockTaken) slock.Exit (false);}}) Parallel.For (0, 100000, I = > {lock (testLock) {sum3 + = I;};}); Console.WriteLine ("value of Num1 is: {0}", sum1); Console.WriteLine ("value of Num2 is: {0}", sum2) Console.WriteLine ("value of Num3 is: {0}", sum3)
Output result:
The value of Num1 is: 1660913202
The value of Num2 is: 4999950000
The value of Num3 is: 4999950000
The value of Num1 is: 2754493646
The value of Num2 is: 4999950000
The value of Num3 is: 4999950000
The value of Num1 is: 4999950000
The value of Num2 is: 4999950000
The value of Num3 is: 4999950000
Finally, take a look at the structure diagram of threadpoll and task:
Threadpool:
Task:
Thank you for reading this article carefully. I hope the article "what's the difference between task and thread in c #" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
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.