C# 等待第一个BackgroundWorker完成后再运行第二个Worker
我想为我的安装制作一份“清单”:C# 等待第一个BackgroundWorker完成后再运行第二个Worker,c#,backgroundworker,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) [ ] InsertDa
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完成后再运行第二个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查询,现在是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
BackgroundWorker已经过时了。通过任务、
async/await
和IProgress
界面,可以使用它的所有功能和更多功能。事实上,可组合性是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
应仅用于事件处理程序。所有其他方法应返回异步任务
或异步任务
<代码>异步无效方法不能等待。它们本质上是“用火而忘却”的方法
如果要组合多个异步调用,只需逐个添加:
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);
}
}
因此,请使用一名工作人员,并给它一个按顺序执行的事情(即代理)列表?我使用一名工作人员,并给他们一个参数yea。我应该创建4个工人吗?因为代码将比:/n大得多,它正在工作,但不会等到第一次
RunWorkerAsync
完成。我还尝试使用AutoResetEvent和waitOne()
,但这将冻结我的主线程并保持冻结状态。在oncomplete中,不要一开始调用run worker 4次,而是调用下一个..Tasks work。这是错误的代码-在任务中使用async void
而不是async task,Thread.Sleep
(为什么?)。当任务是单个异步操作时,使用全局任务。但是,除非您采取特殊的步骤,否则链接BGWs不会起作用。修复使用的代码tasks@PanagiotisKanavosThread.Sleep
只是检查代码是否工作,因为将运行的代码少于1秒^^^@BugFinder,所以你的意思是我应该在RunWorkerCompleted事件中调用下一个BackgroundWorker
这意味着我必须创建4个BackgroundWorker?