?? Multithreading vs. Asynchronous Programming vs. Parallel Programming ??
Sandeep Pal
9+ Exp | C# | Dotnet Core | Web API | MVC 5 | Azure | React Js | Node JS | Microservices | Sql | MySQL | JavaScript | UnitTest | Dapper | Linq | DSA | Entity framework Core | Web Forms | Jquery | MongoDB | Quick Learner
When building high-performance applications in C#, it’s crucial to know how to handle multiple tasks simultaneously. Let’s break down Multithreading, Asynchronous Programming, and Parallel Programming and see when and how to use each one.
?? 1. Multithreading ??
using System;
using System.Threading;
class Program
{
static void Main()
{
Thread thread1 = new Thread(DoWork);
thread1.Start();
thread1.Join(); // Wait for thread1 to finish
Console.WriteLine("Main thread finished.");
}
static void DoWork()
{
Console.WriteLine("Worker thread is doing work...");
Thread.Sleep(2000); // Simulate work
Console.WriteLine("Worker thread finished.");
}
}
?? 2. Asynchronous Programming ?
领英推荐
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
await FetchDataFromAPIAsync();
Console.WriteLine("Main thread continues while waiting...");
}
static async Task FetchDataFromAPIAsync()
{
HttpClient client = new HttpClient();
string result = await client.GetStringAsync("https://api.github.com");
Console.WriteLine("Fetched data from API");
}
}
?? 3. Parallel Programming ??♂???
using System;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static void Main()
{
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var result = numbers.AsParallel().Select(n => ProcessData(n)).ToArray();
Console.WriteLine("Parallel processing complete.");
}
static int ProcessData(int n)
{
Console.WriteLine($"Processing {n} on thread {Thread.CurrentThread.ManagedThreadId}");
return n * n; // Simulate processing
}
}
#CSharp #Multithreading #AsyncProgramming #ParallelProgramming #DotNet #SoftwareDevelopment #Tech #ProgrammingTips