
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
Thread-based parallelism in C#
In C#, Task parallelism divide tasks. The tasks are then allocated to separate threads for processing. In .NET, you have the following mechanisms to run code in parallel: Thread, ThreadPool, and Task. For parallelism, use tasks in C# instead of Threads.
A task will not create its own OS thread, whereas they are executed by a TaskScheduler.
Let us see how to create tasks. Use a delegate to start a task −
Task tsk = new Task(delegate { PrintMessage(); }); tsk.Start();
Use Task Factory to start a task −
Task.Factory.StartNew(() => {Console.WriteLine("Welcome!"); });
You can also use Lambda −
Task tsk = new Task( () => PrintMessage() ); tsk.Start();
The most basic way to start a task is using the run() −
Example
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
- Related Articles
- Thread-based parallelism in Python
- Data parallelism vs Task parallelism
- Parallelism
- Main thread vs child thread in C#
- Thread functions in C/C++
- Thread Pools in C#
- Thread Synchronization in C#
- Types of Parallelism in Processing Execution
- Thread-Safe collections in C#
- Thread get_id() function in C++
- How to get the thread ID from a thread in C#?
- Difference between Concurrency and Parallelism
- Background and foreground thread in C#
- Thread Safe Concurrent Collection in C#
- Threads and Thread Synchronization in C#

Advertisements