Share via

which one is called in asynchrony or parallel

rajesh yadav 291 Reputation points
2025-08-07T12:00:07.9766667+00:00

can i get any example of cuncurrent and parllell processing using asyncrony.

Developer technologies | ASP.NET Core | Other

Answer accepted by question author

Danny Nguyen (WICLOUD CORPORATION) 6,945 Reputation points Microsoft External Staff Moderator
2025-08-08T07:06:33.7233333+00:00

Hi @rajesh yadav ,

You were asking about differences between Asynchrony and Parallelism.

Here's a clear explanation of these concepts


Asynchrony vs Parallelism in C# (.NET)

Asynchrony

Asynchronous programming is about releasing the thread while waiting for an operation to complete. It allows other work to be performed in the meantime.

In simple terms:

  • You start an operation (like reading a file or calling a web service).
  • Instead of waiting for it to finish, your program returns control to the caller or continues doing other work.
  • When the operation finishes, your program resumes from where it left off.

Key points:

  • Asynchrony does not mean multiple things are running at exactly the same instant—it means your program can overlap waiting time with other work.
  • Best for I/O-bound work: database queries, web requests, file operations.

Parallelism

Parallel programming is about using multiple threads (often on multiple processor cores) to execute multiple operations at the same time.

In simple terms:

  • The work is split into smaller pieces.
  • Those pieces are executed simultaneously on different CPU cores.

Key points:

  • Parallelism requires multiple threads actively working at once.
  • Best for CPU-bound work: heavy calculations, data transformations, image processing.

Concurrency

Concurrency is the general ability of your application to make progress on multiple operations at once. Asynchrony and parallelism are two different techniques to achieve concurrency. You may use both at different times depending on whether you're waiting for external operations (asynchrony) or running heavy computation (parallelism).


Examples (Console App)

Example A – Asynchrony (I/O-bound)

This example downloads several web pages without blocking the calling thread. The downloads are started together, and while each one is waiting for the network, other downloads can make progress.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
 
namespace AsyncExample
{
    class Program
    {
        static async Task Main()
        {
            // Three test endpoints that artificially delay responses:
            var urls = new List<string>
            {
                "https://httpbin.org/delay/2", // 2 second server delay
                "https://httpbin.org/delay/3", // 3 second server delay
                "https://httpbin.org/delay/1"  // 1 second server delay
            };
 
            using var client = new HttpClient();
 
            Console.WriteLine("------ Sequential downloads (one after another) ------");
            var sw = Stopwatch.StartNew();
            await SequentialDownloads(client, urls);
            sw.Stop();
            Console.WriteLine($"Sequential total time: {sw.Elapsed.TotalSeconds:F2} seconds\n");
 
            Console.WriteLine("------ Concurrent downloads (start all, await all) ------");
            sw.Restart();
            await ConcurrentDownloads(client, urls);
            sw.Stop();
            Console.WriteLine($"Concurrent total time: {sw.Elapsed.TotalSeconds:F2} seconds\n");
        }
 
        static async Task SequentialDownloads(HttpClient client, List<string> urls)
        {
            foreach (var url in urls)
            {
                Console.WriteLine($"[Sequential] Starting: {url} at {DateTime.Now:HH:mm:ss.fff}");
                string content = await client.GetStringAsync(url); // waits, does not block caller thread
                Console.WriteLine($"[Sequential] Completed: {url} at {DateTime.Now:HH:mm:ss.fff}; Length: {content.Length}");
            }
        }
 
        static async Task ConcurrentDownloads(HttpClient client, List<string> urls)
        {
            // Start all downloads without awaiting each one immediately
            var tasks = urls.Select(url => DownloadWithLog(client, url)).ToList();
 
            // Wait for all to finish
            string[] results = await Task.WhenAll(tasks);
 
            // Print brief summary
            for (int i = 0; i < urls.Count; i++)
            {
                Console.WriteLine($"[Concurrent] {urls[i]} -> {results[i].Length} characters");
            }
        }
 
        static async Task<string> DownloadWithLog(HttpClient client, string url)
        {
            Console.WriteLine($"[Concurrent] Starting: {url} at {DateTime.Now:HH:mm:ss.fff}");
            string content = await client.GetStringAsync(url);
            Console.WriteLine($"[Concurrent] Completed: {url} at {DateTime.Now:HH:mm:ss.fff}");
            return content;
        }
    }
}

What happens here:

  • In the sequential run, the total time is roughly the sum of the delays.
  • In the concurrent run, total time is roughly the maximum of the delays:
    • All downloads start together.
    • While one is waiting for network data, another can progress.
    • The program doesn’t waste time sitting idle—this is the main benefit of asynchrony.

Example B – Parallelism (CPU-bound)

This example count all prime numbers in a range using Parallel LINQ (PLINQ), which automatically splits the work across available CPU cores.

using System;
using System.Diagnostics;
using System.Linq;
 
namespace ParallelExample
{
    class Program
    {
        static void Main()
        {
            // Adjust the range size to make the test fast or heavy on your machine
            int rangeSize = 2_500_000; // try 1_000_000, 2_000_000 depending on your CPU
            var numbers = Enumerable.Range(2, rangeSize);
 
            Console.WriteLine($"Counting prime numbers in range 2..{rangeSize + 1}");
 
            // Sequential (one core, one after another)
            var sw = Stopwatch.StartNew();
            int sequentialCount = numbers.Count(IsPrime);
            sw.Stop();
            Console.WriteLine($"Sequential prime count: {sequentialCount}");
            Console.WriteLine($"Sequential elapsed: {sw.Elapsed.TotalSeconds:F2} seconds\n");
 
            // Parallel (use multiple cores if available)
            sw.Restart();
            int parallelCount = numbers.AsParallel().Count(IsPrime);
            sw.Stop();
            Console.WriteLine($"Parallel prime count: {parallelCount}");
            Console.WriteLine($"Parallel elapsed: {sw.Elapsed.TotalSeconds:F2} seconds\n");
 
            Console.WriteLine("Note: results should match. Parallel run will often be faster on systems with multiple cores.");
        }
 
        static bool IsPrime(int n)
        {
            if (n < 2) return false;
            int limit = (int)Math.Sqrt(n);
            for (int i = 2; i <= limit; i++)
            {
                if (n % i == 0) return false;
            }
            return true;
        }
    }
}

What happens here:

  • The sequential version runs the prime check on each number one after another.
  • The parallel version uses a feature that splits the range into parts and evaluates them on multiple threads at the same time, usually reducing elapsed time on multi-core processors:
    • The collection is split into chunks.
    • Each chunk is processed on a separate CPU core at the same time.
    • This reduces total computation time for CPU-heavy tasks.
  • For small ranges, the parallel version may not help and could be slower because splitting and scheduling work costs time. For larger ranges the parallel version typically wins.

Choosing approach:

Asynchrony:

  • Downloading files from the internet
  • Reading large files from disk Parallelism:
  • Performing complex mathematical models
  • Processing image filters on many images

Additional documentations: These documents can give you better understanding on asynchronous and parallel programming in .NET products:


Hope you find this helpful, please reach out if you need any clarification

Was this answer helpful?


2 additional answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 84,071 Reputation points
    2025-08-07T18:08:40.51+00:00

    concurrency is when a program performs more than one operation at the same time. on a single processor concurrency can be performed by cooperative operation. that is a operation yields to another before its completed such as using co-routines or threads (where a scheduler controls when the thread runs).

    parallelism is when the concurrent work is performed at the same time using multiple cpus. this can be done via threads or async operations.

    many api call to the O/S are async by nature. say performing I/O. the cpu is not used during disk seeks or data transfers to the O/S memory buffer. the same with a network request. the O/S may expose these as single threaded async routines, that make a callback when completed. if the O/S block the api on an asynchronous api call, you can use a thread to make it async.

    using threads you can also make a compute task async

    so while an async operation is running, the code can perform other operations. this work even with a single cpu computer.

    // run sync code async
    var task1 = Task.Run(() => doSomthing1());
    // sync code running during async
    doSomthing2();
    // wait for async task to complete
    await task1;
    

    parallelism often refers to breaking a code into steps that can be run in separate cpus at the same time. modern cpu's do this and som compilers. using compute thread you can write code that does this.

    // parallel sync code via tasks
    var task1 = Task.Run(() => doSomthing1());
    var task2 = Task.Run(() => doSomthing2());
    await Task.WhenAll(task1,task2);
    

    note: many functional languages have built in support for parallelism, as functional methods and immutable values allow more parallelism via the compiler.

    Was this answer helpful?

    0 comments No comments

  2. SurferOnWww 6,016 Reputation points
    2025-08-07T13:23:05.1966667+00:00

    which one is called in asynchrony or parallel

    Although I do not know what you mean by "which one is called in asynchrony or parallel" ...

    can i get any example of cuncurrent and parllell processing using asyncrony.

    How about the following example? Note that the example is .NET 9.0 Console app.

    namespace ConsoleAppTPL
    {
        internal class Program
        {
            static async Task Main(string[] args)
            {
                int minWorker; // Minimum number of worker threads
                int minIOC;    // Minimum number of async I/O threads
                ThreadPool.GetMinThreads(out minWorker, out minIOC);
                Console.WriteLine($"minWorker: {minWorker}, minIOC: {minIOC}");
    
                int maxWorker; // Maximum number of worker threads
                int maxIOC;    // Maximum number of async I/O threads
                ThreadPool.GetMaxThreads(out maxWorker, out maxIOC);
                Console.WriteLine($"maxWorker: {maxWorker}, maxIOC: {maxIOC}");
    
                var prog = new Program();
    
                //await prog.TaskRunAsync();
    
                await prog.ParallelInvokeAsync();
            }
    
            // sync method Work
            public string Work(int number)
            {
                int id = Thread.CurrentThread.ManagedThreadId;
                DateTime start = DateTime.Now;
                string retunVlaue = $"n = {number}, ThreadID = {id}" +
                                    $", start: {start:ss.fff}, ";
    
                // 3 seconds delay
                // See the Additional Info in my comment below
                Task.Delay(3000).Wait();
    
                DateTime end = DateTime.Now;
                TimeSpan diff = start - end;
                retunVlaue += $"end: {end:ss.fff}, timespan: {diff:s\\.fff}";
                return retunVlaue;
            }
    
            // Queues 25 sync methods to run on the ThreadPool.
            // Windows OS obtains thread form the TreadPool and executes the methods.
            // Waits for completion of all the methods using await Task.WhenAll.
            public async Task TaskRunAsync()
            {
                int id = Thread.CurrentThread.ManagedThreadId;
                DateTime start = DateTime.Now;
                Console.WriteLine($"Main Thread ID = {id}, " +
                    $"TaskRunAsync start: {start:ss.fff}");
                string[] stringResults = new string[25];
                var taskList = new List<Task>();
                for (int i = 0; i < 25; i++)
                {
                    int n = i;
                    taskList.Add(Task.Run(() => stringResults[n] = Work(n)));
                }
    
                await Task.WhenAll(taskList);
    
                foreach (string result in stringResults)
                {
                    Console.WriteLine(result);
                }
    
                DateTime end = DateTime.Now;
                TimeSpan diff = start - end;
                Console.WriteLine($"Main Thread ID = {id}, " +
                    $"end: {end:ss.fff}, Timespan: {diff:s\\.fff}");
            }
    
            // Executes 25 sync methods parallely using Parallel.Invoke
            public async Task ParallelInvokeAsync()
            {
                int id = Thread.CurrentThread.ManagedThreadId;
                DateTime start = DateTime.Now;
                Console.WriteLine($"Main Thread ID = {id}, " +
                    $"ParallelInvokeAsync strat: {start:ss.fff}");
                string[] stringResults = new string[25];
                Action[] actions = new Action[25];
                for (int i = 0; i < 25; i++)
                {
                    int n = i;
                    actions[n] = () => stringResults[n] = Work(n);
                }
    
                await Task.Run(() => Parallel.Invoke(actions));
    
                foreach (string result in stringResults)
                {
                    Console.WriteLine(result);
                }
    
                DateTime end = DateTime.Now;
                TimeSpan diff = start - end;
                Console.WriteLine($"Main Thread ID = {id}, " +
                    $"end: {end:ss.fff}, timespan: {diff:s\\.fff}");
            }
        }
    }
    

    Result of TaskRunAsync

    enter image description here

    Result of ParallelInvokeAsync

    enter image description here

    Was this answer helpful?


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.