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 in C# by jyoti
• 1,240 points
27 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 by krishna
• 2,640 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 in C# by pranav
• 2,580 points
23 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 in C# by rajiv
• 1,620 points
54 views
0 votes
1 answer

When to use abstract classes

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

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

How to iterate over a dictionary?

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

answered Jun 7 in C# by pranav
• 2,580 points
29 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 in C# by rajiv
• 1,620 points
32 views
0 votes
1 answer
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
701 views
0 votes
1 answer

Validate String against USPS State Abbreviations

Try something like this: private static String states ...READ MORE

answered Sep 20, 2018 in IoT (Internet of Things) by Annie97
• 2,160 points
243 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 in C# by krishna
• 2,640 points
33 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 in C# by krishna
• 2,640 points
39 views
webinar REGISTER FOR FREE WEBINAR X
Send OTP
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP