Home >Backend Development >C#.Net Tutorial >Thread-based parallelism in C#

Thread-based parallelism in C#

王林
王林forward
2023-09-11 16:09:02806browse

C# 中基于线程的并行性

In C#, tasks are divided into tasks in parallel. The task is then assigned to a separate thread for processing. In .NET, you can run code in parallel using the following mechanisms: threads, thread pools, and tasks. To achieve parallelism, use tasks instead of threads in C#.

Tasks do not create their own operating system threads, but are executed by TaskScheduler.

Let's see how to create a task. Use delegates to start tasks -

Task tsk = new Task(delegate { PrintMessage(); });
tsk.Start();

Use task factories to start tasks -

Task.Factory.StartNew(() => {Console.WriteLine("Welcome!"); });

You can also use Lambda -

Task tsk = new Task( () => PrintMessage() );
tsk.Start();

The most basic way to start tasks is to use run() -

Example

Real-time demonstration

using System;
using System.Threading.Tasks;

public class Example {
   public static void Main() {
      Task tsk = Task.Run(() => {
         int a = 0;
         for (a = 0; a <= 1000; a++) {}
         Console.WriteLine("{0} loop iterations ends", a);
      });
      tsk.Wait();
   }
}

Output

1001 loop iterations ends

The above is the detailed content of Thread-based parallelism in C#. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete