Thread-based parallelism in C#

王林
Release: 2023-09-11 16:09:02
forward
747 people have browsed it

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();
Copy after login

Use task factories to start tasks -

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

You can also use Lambda -

Task tsk = new Task( () => PrintMessage() );
tsk.Start();
Copy after login

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();
   }
}
Copy after login

Output

1001 loop iterations ends
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!