C# async deadlock - why is it happening in this case

362 Views Asked by At

I have an ASP.Net application (actually Lightswitch is involved here, not sure that it matters much in this case).

I have the following code. It starts in the LogIn.aspx which calls RegisterUser on the OnLoggedIn event.

    public static void RegisterUser(string userName)
    {
        using (var connection = new SqlConnection(IzendaSettings.ConnectionString))
        using (var command = connection.CreateCommand())
        {
            connection.Open();
            command.CommandText = @"SELECT CU.DisplayName, CU.ClientId, C.Name FROM ClientUser CU INNER JOIN Client C on C.ClientId = CU.ClientId WHERE CU.UserName = @userName AND Rights = 0";
            command.Parameters.Add("userName", SqlDbType.NVarChar).Value = userName; 
            using (var reader = command.ExecuteReader())
            {
                if (reader.Read())
                {
                    var unused = RegisterUserAsync(userName, reader.GetString(0), reader.GetInt32(1).ToString(), reader.GetString(0));
                }
            }
        }
    }

    internal static async Task RegisterUserAsync(string userName, string fullName, string clientId, string clientName)
    {
        try
        {
            var token = TokenAuthorization.GetSystemAdministratorToken();
            while (Bootstrap.Initalizing)
            {
                Thread.Yield();
            }
            var izenda = await TenantProcess.Initialize(clientId, clientName, token);
            var connection = await izenda.SetUpConnection(IzendaSettings.ConnectionString);
            await izenda.PutUserInRole("User", userName, fullName, "~/BI/tenantRolePermission.json", connection);
        }
        catch (Exception e)
        {
            Logger.Error("Register User", e);
        }
    }

The async code deadlocks. I'm trying to just run it off in a separate thread, I don't await it on purpose.

Changing the call to RegisterUserAsync to this (with the appropriate capture of the SQL prior to launching the thread):

Task.Run(() => RegisterUserAsync(userName, user.FullName, user.ClientId, user.ClientName));

Solves the problem. I understand why calling Task.Run solves an async call that you want to wait for without deadlocking, but I don't understand why in this case the deadlock was happening. (The Initializing variable was false - I logged a debug statement to make sure, so it never actually did the Thread.Yield, but I wouldn't see why that would affect it anyway).

Why was the deadlock happening in the old code?

0

There are 0 best solutions below