简体   繁体   中英

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.

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); 
}

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;
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM