Waiting for async function to finish

I have a problem, I want to make the asynchrnous function to finish first before going to the next one. Why? Because the value of the function is needed to the next line of code.

I tried, await, wait(), RunSynchronous but it is not working. It still proceeds to execute other lines of code.

This is my code: It is the default Login for ASP.NET MVC5 but what I want to do is change the redirect depending on the user.

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            var user = await UserManager.FindAsync(model.UserName, model.Password);
            if (user != null)
            {     
                          SignInAsync(user, model.RememberMe);
                         RedirectToLocal(LogInRedirect());
            }
            else
            {
                ModelState.AddModelError("", "Invalid username or password.");
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

I have a custom parameter called UserDepartment and I can only retrieve it after SignInAsync(user, model.RememberMe); finish executing.

This is the code for SignInAsync

    private async Task SignInAsync(ApplicationUser user, bool isPersistent)
    {
        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
        var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
         AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity); 
    }

What should I do to achieve my goal that SignInAsync should finish first before proceeding to other line of code.

EDIT: So await works, but there is another problem. SignInAsync is not yet finish but it already return that it is completed. By finish I mean the execution of code, I trace the execution but there are times that AuthenticationManager.SignIn is not yet finish but still return it is

Upvotes: 1

Views: 2648

Answers (1)

James
James

Reputation: 82096

You need to await the result of the SignInAsync call

await SignInAsync(user, model.RememberMe);
...

You internally await the result of the UserManager.CreateIdentityAsync method so that will block until that result returns inside the SignInAsync method. However, without awaiting the call to SignInAsync itself, the code won't block which is why the next line is called immediately.

Upvotes: 1

Related Questions