简体   繁体   中英

How to call async Task<bool> method?

This is the async function i have created, here am getting error while claaing this function on buttion click.

public async Task<bool> Login(string UserName, string Password)
    {
        try
        {
            ParseUser User = await ParseUser.LogInAsync(UserName, Password);
            System.Windows.Forms.MessageBox.Show(User.ObjectId);
            var currentUser = ParseUser.CurrentUser;
            return true;
        }
        catch (Exception ex)
        {
            System.Windows.Forms.MessageBox.Show(ex.Message);
            return false;
        }           
    }

its getting error while calling.

private void btnLogin_Click(object sender, EventArgs e)
    {
        if (Login(txtUserName.Text,txtPassword.Text))
        {
            MessageBox.Show("Login Success");                       
        }            
    }

You need to asynchronously wait for the Login method like this:

private async void btnLogin_Click(object sender, EventArgs e)
{
    if (await Login(txtUserName.Text,txtPassword.Text))
    {
        MessageBox.Show("Login Success");                       
    }            
}

Now, this event handler is asynchronous (by using the async keyword) and it asynchronously waits for the Login method (by using the await keyword).

Please note that in general, it is not recommended to have async void methods. However, one exception for this rule are event handlers. So this code is fine.

You need to asynchronously wait for the method as shown below:

 private async void btnLogin_Click(object sender, EventArgs e) {
 var task = Login(txtUserName.Text, txtPassword.Text)
 var result = await task;
 if (result) {
  MessageBox.Show("Login Success");
 }
}

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