Home >Backend Development >C#.Net Tutorial >Thread-based parallelism in 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() -
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(); } }
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!