Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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");                       
        }            
    }
like image 250
Rendeep Avatar asked Dec 31 '15 10:12

Rendeep


People also ask

How do I assign a value to a task in Boolean?

To return Boolean from Task Synchronously, we can use Task. FromResult<TResult>(TResult) Method. This method creates a Task result that's completed successfully with the specified result. The calling method uses an await operator to suspend the caller's completion till called async method has finished successfully.

How do you call a method in asynchronous in C#?

The simplest way to execute a method asynchronously is to start executing the method by calling the delegate's BeginInvoke method, do some work on the main thread, and then call the delegate's EndInvoke method. EndInvoke might block the calling thread because it does not return until the asynchronous call completes.

How do you call async method without await?

@Servy async creates a state machine that manages any awaits within the async method. If there are no await s within the method it still creates that state machine--but the method is not asynchronous. And if the async method returns void , there's nothing to await. So, it's more than just awaiting a result.


1 Answers

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.

like image 125
Yacoub Massad Avatar answered Sep 27 '22 22:09

Yacoub Massad