Author - StudySection Post Views - 57 views
Asynchronous programming

Asynchronous Programming

Asynchronous programming is an effective solution for blocked or delayed access to resources. Suppose an activity in a synchronous process is blocked in a way, that the entire program must wait, which increases processing time.

It should be used if your demands are I/O-bound (for example, reading and writing to a file system, accessing a database, or requesting data via a network). Another case that is advantageous for developing async code is when you have CPU-bound code, such as when you are conducting an expensive calculation.

Async programming in C# uses the async and await keywords. You can use them to work with .NET Framework and.NET Core resources, among other things. Async methods are asynchronous methods specified with the async keyword.

Async

This keyword designates a function as being asynchronous. To put it another way, we can invoke a function asynchronously if we prefix it with the async keyword.
public async void CallAnyfunction() { }

Await

We do use this keyword when calling any function asynchronously.
Suppose we have a long-running process.
static void Main()
{
var count = await Method1(); //used await keyword
Method2(count); //dependent on method1
}
public static async Task<int> Method1()
{
int count = 0;
await Task.Run(() =>
{
for (int i = 0; i < 100; i++)
{
Console.WriteLine(" Method 1");
count += 1;
}
});
return count;
}
public static void Method2(int count)
{
Console.WriteLine("Total count is " + count);
}

Advantages of using this approach:

  • Maintain UI responsiveness
  • Possibility of improving performance by parallel processing
  • Avoid running out of the thread pool by “stopping” execution during asynchronous activity and freeing threads into the thread pool.
  • Performance Improvement

If you have skills in PHP programming and you want to enhance your career in this field, a PHP certification from StudySection can help you reach your desired goals. Both beginner level and expert level PHP Certification Exams are offered by StudySection along with other programming certification exams.

Leave a Reply

Your email address will not be published.