简体   繁体   English

如何调用异步任务 <bool> 方法?

[英]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: 您需要异步等待Login方法,如下所示:

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). 现在,此事件处理程序是异步的(通过使用async关键字),并异步等待Login方法(通过使用await关键字)。

Please note that in general, it is not recommended to have async void methods. 请注意,一般情况下,不建议使用async void方法。 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");
 }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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