How and when to use async and await

0 votes

One of the key benefits of async and await, in my opinion, is that they make code easier to write and comprehend; nevertheless, is utilising them equivalent to creating background threads to do long-running logic?

I'm currently putting the most basic example to the test. Inline comments have been added. Could you please explain it to me?

// I don't understand why this method must be marked as `async`.
private async void button1_Click(object sender, EventArgs e)
{
    Task<int> access = DoSomethingAsync();
    // task independent stuff here

    // this line is reached after the 5 seconds sleep from 
    // DoSomethingAsync() method. Shouldn't it be reached immediately? 
    int a = 1; 

    // from my understanding the waiting should be done here.
    int x = await access; 
}

async Task<int> DoSomethingAsync()
{
    // is this executed on a background thread?
    System.Threading.Thread.Sleep(5000);
    return 1;
}
Jun 11, 2022 in C# by jyoti
• 1,240 points
550 views

1 answer to this question.

0 votes

The compiler creates a state machine in the background when async and await are used.

I'll try to illustrate some of the high-level details by using the following example:

public async Task MyMethodAsync()
{
    Task<int> longRunningTask = LongRunningOperationAsync();
    // independent work which doesn't need the result of LongRunningOperationAsync can be done here

    //and now we call await on the task 
    int result = await longRunningTask;
    //use the result 
    Console.WriteLine(result);
}

public async Task<int> LongRunningOperationAsync() // assume we return an int from this long running operation 
{
    await Task.Delay(1000); // 1 second delay
    return 1;
}

So this is what happens in the code above:

1. Task<int> longRunningTask = LongRunningOperationAsync(); starts running LongRunningOperation

2. Non- dependent work is finished on let's say some main thread (Thread ID = 1) then await LongRunningTask is reached.

MyMethodAsync() will now return to the calling method if the longRunningTask hasn't finished yet, preventing the main thread from becoming blocked. Any thread from the ThreadPool will return to MyMethodAsync() in its previous context after the longRunningTask has completed and continue to run (in this case printing the result to the console).

answered Jul 4, 2022 by krishna
• 2,820 points

Related Questions In C#

0 votes
0 answers

When to use an interface instead of an abstract class and vice versa

This could be an OOP question in ...READ MORE

Jun 11, 2022 in C# by pranav
• 2,590 points
380 views
0 votes
1 answer

Which design pattern to use for pre-process process and post-process task

You have pre-defined and precise steps to ...READ MORE

answered Jun 9, 2022 in C# by rajiv
• 1,620 points
1,807 views
0 votes
1 answer

When to use abstract classes

When you need a class for inheritance ...READ MORE

answered Jun 17, 2022 in C# by jyoti
• 1,240 points
571 views
0 votes
1 answer

How to iterate over a dictionary?

I have seen this being used. In ...READ MORE

answered Jun 7, 2022 in C# by pranav
• 2,590 points
459 views
0 votes
1 answer

Why program working differently on every run when using async?

You can use the async Main method ...READ MORE

answered May 30, 2022 in C# by rajiv
• 1,620 points
565 views
0 votes
0 answers

Convert async Task from c# to vb.net

I'm using a C# to VB.NET converter ...READ MORE

Dec 12, 2022 in C# by Roshan
• 300 points
1,597 views
0 votes
1 answer

SQLite.Net not being able to create text file in Win IoT Library!

That exception comes when access limited to ...READ MORE

answered Aug 3, 2018 in IoT (Internet of Things) by nirvana
• 3,130 points
1,013 views
0 votes
2 answers

Is there a .NET equivalent to Apache Hadoop?

Hadoop is a Java-based platform. So, to ...READ MORE

answered Jul 16, 2020 in Big Data Hadoop by Suhana
• 340 points
1,737 views
0 votes
1 answer

How to quickly code and run small C# code

I personally use this LINQPad for this. ...READ MORE

answered Jun 23, 2022 in C# by krishna
• 2,820 points
527 views
0 votes
1 answer

How to initialize a list of strings (List<string>) with many string values

Simply remove the () at the end. List<string> ...READ MORE

answered Jun 13, 2022 in C# by krishna
• 2,820 points
1,749 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP