refactor
refactor

Reputation: 15044

async / await not working

I have written a sample .net win forms application to learn async/await concept.

My sample win form has 2 buttons[button1,button2] ,and below are the click event handlers for both.

private async void button1_Click(object sender, EventArgs e)
{            
  string str = await BL.LongRunningOperation();
  MessageBox.Show(str); 
}

private void button2_Click(object sender, EventArgs e)
{
  MessageBox.Show("Any Time");
}

Below is the long running operation ,which gets invoked on click event of button1

public class BL
{

    public  static async Task<string> LongRunningOperation()
    {
        string strReturnValue = "Long Running Operation";

        int i = 0;

        while (i <= 1000000000)
        {
            i++;
        }

        return strReturnValue;
    }
}

My assumption was once the user clicks the Button1 , the long running operation will get executed asynchronously, and in the mean time user can click button2.

But what I observed is that,user is able to click button2 only once long running operation gets completed.

Please let me know what needs to be modifed to make this call async.

Upvotes: 0

Views: 1101

Answers (2)

kirotab
kirotab

Reputation: 1306

As is your example is executing synchronously so you might try wrapping your long running operation body in a

public static async Task<string> LongRunningOperation()
{
    return await Task.Run(()=>
    {
        string strReturnValue = "Long Running Operation";

        int i = 0;

        while (i <= 1000000000)
        {
            i++;
        }

        return strReturnValue;
    });
}

Upvotes: 3

Sean
Sean

Reputation: 62472

Your LongRunningOperation doesn't actually do anything asynchronously, so it won't run on another thread and return to the click handler. There should have been a compiler warning about this as your async method doesn't have an await in it.

As suggested by other answers, write your click handler like this:

private async void button1_Click(object sender, EventArgs e)
{            
  string str = await Task.Run(() => BL.LongRunningOperation());
  MessageBox.Show(str); 
}

Upvotes: 8

Related Questions