等到第一个BackgroundWorker完成后再运行第二个Worker

时间:2018-02-07 11:48:42

标签: c# backgroundworker

我想做一个"清单"我的安装:

1st Create Table
2nd Add PrimaryKey
3rd Set AutoIncrement
4th InsertData

所以我制作了4个BackgroundWorkers,因为每个步骤都使用了加载动画:

[X] Create Table (Finished)
[...] Add Primary Key (In process)
[ ] Set AutoIncrement (Didn't loaded yet)
[ ] InsertData (didn't loaded yet)

问题是,代码不会等到第一个BackgroundWorker完成后再运行第二个。

这是我现在的准则:

if (result == MessageBoxResult.Yes)
{
    DialogHostLoading.IsOpen = true;
    if (worker.IsBusy)
        {
            worker.CancelAsync();
            worker.RunWorkerAsync();
            MessageBox.Show("IsBusy");
        }
        else
        {
            if(!isError)
            {
                #region CreateTable
                tableIcon.Visibility = Visibility.Collapsed;
                tableIconLoading.Visibility = Visibility.Visible;
                worker.RunWorkerAsync("CreateTable");
                #endregion

                #region SetPrimaryKey
                setPrimaryKeyIcon.Visibility = Visibility.Collapsed;
                setPrimaryKeyLoading.Visibility = Visibility.Visible;
                worker.RunWorkerAsync("SetPrimaryKey");
                #endregion

                #region SetAutoIncrement
                setAutoIncrementIcon.Visibility = Visibility.Collapsed;
                setAutoIncrementLoading.Visibility = Visibility.Visible;
                worker.RunWorkerAsync("SetAutoIncrement");
                #endregion


                // Close Dialog if finished without Errors
                DialogHostLoading.IsOpen = false;
                MessageBox.Show("Import erfolgreich.");
            }
            else
            {
                if(!string.IsNullOrEmpty(ErrorMessageString))
                {
                    MessageBox.Show(ErrorMessageString);
                    DialogHostLoading.IsOpen = false;
                    ErrorMessageString = string.Empty;
                }
                else
                {
                    Debug.WriteLine("isError = true BUT ErrorMessageString is null or empty");
                }

            }
        }

DoWork是SQL Querys,现在是RunWorkerCompleted事件:

private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if(e.Result.GetType() == typeof(string))
    {
        Color redColor = (Color)ColorConverter.ConvertFromString("#DDC31616");
        Color greenColor = (Color)ColorConverter.ConvertFromString("#DD15992D");
        switch (e.Result)
        {
            case "CreateTable":
                if(string.IsNullOrEmpty(ErrorMessageString))
                {
                    tableIcon.Foreground = new SolidColorBrush(redColor);
                    tableIcon.Kind = MaterialDesignThemes.Wpf.PackIconKind.CloseCircle;
                    tableIconLoading.Visibility = Visibility.Collapsed;
                    tableIcon.Visibility = Visibility.Visible;
                    isError = true;
                }
                else
                {
                    tableIcon.Foreground = new SolidColorBrush(greenColor);
                    tableIcon.Kind = MaterialDesignThemes.Wpf.PackIconKind.CheckCircle;
                    tableIconLoading.Visibility = Visibility.Collapsed;
                    tableIcon.Visibility = Visibility.Visible;
                }
                break;
            case "SetPrimaryKey":
                if(string.IsNullOrEmpty(ErrorMessageString))
                {
                    setPrimaryKeyIcon.Foreground = new SolidColorBrush(redColor);
                    setPrimaryKeyIcon.Kind = MaterialDesignThemes.Wpf.PackIconKind.CloseCircle;
                    setPrimaryKeyLoading.Visibility = Visibility.Collapsed;
                    setPrimaryKeyIcon.Visibility = Visibility.Visible;
                    isError = true;
                }
                else
                {
                    setPrimaryKeyIcon.Foreground = new SolidColorBrush(greenColor);
                    setPrimaryKeyIcon.Kind = MaterialDesignThemes.Wpf.PackIconKind.CheckCircle;
                    setPrimaryKeyLoading.Visibility = Visibility.Collapsed;
                    setPrimaryKeyIcon.Visibility = Visibility.Visible;
                }
                break;
        }
    }
}

我尝试使用其他解决方案的异步任务,这对我来说并不起作用:

private readonly Task _CreateTable;
public MainWindow()
{
    InitializeComponent();
    _CreateTable = PerformCreateTableAsync();
}
private async Task PerformCreateTableAsync()
    {
        await Task.Run(() =>
        {
            Thread.Sleep(TimeSpan.FromSeconds(5));
        });
    }

    private async void CreateTable()
    {
        Color redColor = (Color)ColorConverter.ConvertFromString("#DDC31616");
        Color greenColor = (Color)ColorConverter.ConvertFromString("#DD15992D");

        tableIcon.Visibility = Visibility.Collapsed;
        tableIconLoading.Visibility = Visibility.Visible;

        await _CreateTable;

        tableIcon.Foreground = new SolidColorBrush(greenColor);
        tableIcon.Kind = MaterialDesignThemes.Wpf.PackIconKind.CheckCircle;
        tableIconLoading.Visibility = Visibility.Collapsed;
        tableIcon.Visibility = Visibility.Visible;
    }

我现在调用RunWorkerAsync我通过以下方式调用任务:

#region CreateTable
CreateTable();
#endregion

1 个答案:

答案 0 :(得分:1)

BackgroundWorker已过时。通过任务async/awaitIProgress< T>界面可以获得其所有功能和更多功能。事实上,可组合性是BGW最大的弱点之一。

使用async / await实际上比使用BGW容易得多。如果您想执行操作以响应例如按钮点击,您可以写下:

private async Task CreateTableAsync(string tableName)
{
    //Execute SQL code that creates a table
    using(var connection=new SqlConnection(_connString)
    using(var cmd=new SqlCommand(connection,sql))
    {
        ....
        await cmd.ExecuteNonQueryAsync();
    }
}

private async void MyButton_Click(object sender, EventArgs args)
{
    Color redColor = (Color)ColorConverter.ConvertFromString("#DDC31616");
    Color greenColor = (Color)ColorConverter.ConvertFromString("#DD15992D");

    tableIcon.Visibility = Visibility.Collapsed;
    tableIconLoading.Visibility = Visibility.Visible;

    try 
    {
        await CreateTableAsync("SomeTableName");

        tableIcon.Foreground = new SolidColorBrush(greenColor);
        tableIcon.Kind = MaterialDesignThemes.Wpf.PackIconKind.CheckCircle;
        tableIconLoading.Visibility = Visibility.Collapsed;
        tableIcon.Visibility = Visibility.Visible;
    }
    catch(Exception exc)
    {
        MessageBox.Show(exc.ToString(),"Ouch!");
    }
}

请注意,async void只应用于事件处理程序。所有其他方法应返回async Taskasync Task<T>。等待async void等方法 。它们本质上是一种即发即弃的方法。

如果你想组合多个异步调用,你唯一需要做的就是一个接一个地添加它们:

private async void MyButton_Click(object sender, EventArgs args)
{
    SetWorkingModeUI();
    try 
    {
        await CreateTableAsync("SomeTableName");
        await CreateTableAsync("OtherTableName");
        await CreateTableAsync("ThirdTableName");

        SetIdleModeUI();
    }
    catch(Exception exc)
    {
        SomeProperErrorHandlerAndLogger(exc);
    }
}

您甚至可以并行运行多个操作并等待所有操作完成:

private async void MyButton_Click(object sender, EventArgs args)
{
    SetWorkingModeUI();
    try 
    {
        var tasks = new[] {
                   AsyncCall1(),
                   AsyncCall2(),
                   AsyncCall3()
        };
        await Task.WhenAll(tasks);

        SetIdleModeUI();
    }
    catch(Exception exc)
    {
        SomeProperErrorHandlerAndLogger(exc);
    }
}