Mulithreading / Asynchronous programming¶
Normally, C# runs code line by line (synchronously). Multithreading allows multiple operations to run at the same time, improving performance. Think of it like multitasking.
Understanding Multithreading vs. Async: When you run a program.exe, Windows creates a process. A process contains everything needed to run the program. The actual code execution happens inside threads.
Multithreading: Uses multiple threads to perform tasks at the same time.
Asynchronous Programming: A single thread handles multiple tasks by switching between them instead of waiting.
Two Ways to Run Code Concurrently:
- Using Threads (System.Threading)
- Using Tasks (System.Threading.Tasks) (preferred for modern async code)
Creating a Thread using System.Threading¶
Each method runs in a separate thread so they execute simultaneously.
Async using System.Threading.Tasks¶
Using Task is preferred over Thread in modern C#. Task is a modern alternative to threads, it's more efficient and works well with async programming.
[!NOTE] Note however that when you're using Tasks, mixing thread-objects within task-objects like:
Thread.Sleep(500);could cause several issues.