简体   繁体   中英

How to make parallel Tasks and wait for a Task to finish

I have a animation bar that I want to show after a user has clicked a button. As the animation is going, I want another task to verify that the user information is correct (Login). When the task is finished I want the animation task to stop and display if the credentials were correct.

I've tried making different Tasks but it gets very complicated and complex and I start to lose my self in a complex code.

public async Task LoadingAnimationAsync()
//Animation
{
    this.pictureBox1.Hide();
    this.badPasswordLabel.Hide();
    this.pictureBox2.Hide();
    this.loadingLabel.Show();
    this.loadingProgressBar.Show();
    this.twitchPicture.Hide();
    this.usernameTB.Hide();
    this.passwordTB.Hide();
    this.loginButton.Hide();

    await Task.Delay(5000);

    this.pictureBox1.Show();
    this.pictureBox2.Show();
    this.loadingLabel.Hide();
    this.loadingProgressBar.Hide();
    this.twitchPicture.Show();
    this.usernameTB.Show();
    this.passwordTB.Show();
    this.loginButton.Show();
}
//Code
await LoadingAnimationAsync();

await Task.Run(() =>
{
    bool TryLogin = Login.CheckForCredentials(usernameTB.Text, passwordTB.Text);

    if (TryLogin == true)
    {
        MainPanel.Show();
        MainPanel.BringToFront();
    }
    else
    {
        this.badPasswordLabel.Show();
    }
});
//CredentialsCheck
public static bool CheckForCredentials(string Username, string Password)
{
    string commandText = "SELECT * FROM Account WHERE Username = @USERNAME AND Password = @PASSWORD";

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(commandText, connection);
        command.Parameters.AddWithValue("@USERNAME", Username);
        command.Parameters.AddWithValue("@PASSWORD", Password);
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        try
        {
            if (reader.Read())
            {
                string CheckAcc = (String.Format("{0}, {1}",
                reader["Username"], reader["Password"]));// etc
                if (CheckAcc.Length > 0)
                {
                    Console.WriteLine("Ima ga");
                    return true;
                }
            }
            Console.WriteLine("Nema ga");
            return false;
        }
        finally
        {
            // Always call Close when done reading.
            reader.Close();
        }
    }
}

Make check for credentials async and then you will be able to write UI code as usual without explicitly creating a Task

private async Task<TResult> RequestWithAnimation<TResult>(Func<Task<TResult>> request)
{
    this.pictureBox1.Hide();
    this.badPasswordLabel.Hide();
    this.pictureBox2.Hide();
    this.loadingLabel.Show();
    this.loadingProgressBar.Show();
    this.twitchPicture.Hide();
    this.usernameTB.Hide();
    this.passwordTB.Hide();
    this.loginButton.Hide();

    var result = await request();

    this.pictureBox1.Show();
    this.pictureBox2.Show();
    this.loadingLabel.Hide();
    this.loadingProgressBar.Hide();
    this.twitchPicture.Show();
    this.usernameTB.Show();
    this.passwordTB.Show();
    this.loginButton.Show();

    return result;
}

Execution

var credentialsAreValid = 
    await RequestWithAnimation(() => Login.CheckForCredentialsAsync(username, password));

if (credentialsAreValid)
{
    MainPanel.Show();
    MainPanel.BringToFront();
}
else
{
    this.badPasswordLabel.Show();
}

Asynchronous check for credentials

public static Task<bool> CheckForCredentialsAsync(string username, string password)
{
    var query = "SELECT 1 FROM Account WHERE Username=@USERNAME AND Password=@PASSWORD";

    using (var connection = new SqlConnection(connectionString))
    using (var command = new SqlCommand(query, connection))
    {
        var parameters = new[]
        {
            new SqlParameter
            {
                ParameterName = @USERNAME,
                SqlDbType = SqlDbType.Varchar,
                Size = 100,
                Value = username
            },
            new SqlParameter
            {
                ParameterName = @PASSWORD,
                SqlDbType = SqlDbType.Varchar,
                Size = 300,
                Value = password
            }
        };

        command.Parameters.AddRange(parameters);

        await connection.OpenAsync();
        var rowExists = await command.ExecuteScalarAsync();

        return rowExists != null;
    };
}

Use ExecuteScalar instead of reader, because only you want to know is that row exists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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