ASYNCHRONOUS
PROGRAMMING
Presented By: Sushil
Bhattarai
CSIT 6th Semester
CONTENTS
Introduction.
Principal of Asynchrony.
Async/Await keywords in C#.
Worked out Examples.
Conclusion.
INTRODUCTION
Asynchronous programming in C# is an efficient approach for managing
activities that are blocked or delayed.
Unlike synchronous processes, where blocking halts the entire process and
increases wait times, the asynchronous approach allows the application to
continue executing other tasks.
The async and await keywords in C# are core to implementing
asynchronous programming.
PRINCIPAL OF ASYNCHRONY
Focuses on writing long-running functions asynchronously, enabling
concurrency within the function itself, rather than externally.
Key Benefits:
1.I/O-Bound Concurrency: Enhances scalability and efficiency by
managing tasks without tying up threads.
2.Simplified Thread Safety: Reduces code complexity in rich-client
applications by minimizing worker threads.
ASYNC AND AWAIT
KEYWORDS
The Aysnc keyword:
Used to define an asynchronous function.
Allows a function to execute asynchronously without blocking the calling
thread.
Syntax:
public async void CallProcess()
{
// Async logic here
}
The Await keyword:
Enables calling functions asynchronously within an async method.
Pauses the execution of the calling method until the awaited task is
complete.
Example:
public static Task LongProcess()
{
return Task.Run(() =>
{
System.Threading.Thread.Sleep(5000); // Simulating a delay
});
}
// Calling the process asynchronously
await LongProcess();
WORKED OUT EXAMPLE
Key points:
Async Main: The Main method is marked as async so it can use await.
Task Delay: Simulates a delay (e.g., for I/O-bound operations)
Await: Suspends execution of the method until the asynchronous
operation is complete, without blocking the thread.
CONCLUSION
Asynchronous programming allows applications to perform tasks without
blocking, enabling better use of system resources and improving
responsiveness.
It keeps applications responsive, especially in scenarios involving long-
running tasks like I/O operations or API calls.