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");
}
}
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.
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.
@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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With