簡體   English   中英

如何制作並行任務並等待任務完成

[英]How to make parallel Tasks and wait for a Task to finish

我有一個動畫欄,希望在用戶單擊按鈕后顯示。 隨着動畫的進行,我希望執行另一個任務來驗證用戶信息是否正確(登錄)。 任務完成后,我希望動畫任務停止並顯示憑據是否正確。

我嘗試過執行不同的任務,但是它變得非常復雜,而且我開始在復雜的代碼中迷失自我。

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();
        }
    }
}

進行憑據異步檢查,然后您就可以照常編寫UI代碼,而無需顯式創建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;
}

執行

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

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

異步檢查憑據

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;
    };
}

使用ExecuteScalar而不是reader,因為只有您想知道該行是否存在。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM