我以前在Windows窗体应用程序中使用了BackgroundWorker
。
对于我的新练习,我需要在工作者中使用async
方法,我对此感到有些困惑。
这是我的代码结构。在表单加载事件中,我正在创建BackgroundWorker
对象和设置事件
private void fMain_Load( object sender, EventArgs e ) {
bw = new BackgroundWorker();
bw.WorkerReportsProgress = true;
bw.DoWork += new DoWorkEventHandler( bw_DoWork );
bw.ProgressChanged += new ProgressChangedEventHandler( bw_ProgressChanged );
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler( bw_RunWorkerCompleted );
}
当用户点击按钮时,我正在启动工作人员
private void btnGenerate_Click( object sender, EventArgs e ) {
Settings settings = new Settings();
pbCounter.Visible = true;
btnGenerate.Enabled = false;
bw.RunWorkerAsync( settings );
}
这是工人代码
private async void bw_DoWork( object sender, DoWorkEventArgs e ) {
try {
for ( int ix = 1; i <= 100; i++ ) {
using (var client = new HttpClient()) {
[???? how to call and wait here ????]
HttpResponseMessage response = await client.PostAsync( "endpoint", new StringContent( JsonConvert.SerializeObject( formContent ), Encoding.UTF8, "application/json" ) );
}
//The counter will keep track of your process
Application.DoEvents();
int percentage = ix * 100 / settings.TotalRuns;
bw.ReportProgress( percentage );
}
}
catch ( Exception ex ) {
MessageBox.Show( ex.Message, "Gift Creator", MessageBoxButtons.OK, MessageBoxIcon.Error );
}
}
答案 0 :(得分:3)
如果您使用async
和await
,则无需后台工作人员。事实上,您的后台工作程序无法工作,因为当您使用await
时,控件会返回给调用者。当DoWork
处理程序将控制权返回给其调用者时,后台工作程序将终止而不继续其retainnig任务。
所以我会创建按钮处理程序async
并在那里执行http请求:
private async void btnGenerate_Click(object sender, EventArgs e)
{
const int totalRuns = 5;
pbCounter.Visible = true;
pbCounter.Minimum = 0;
pbCounter.Maximum = totalRuns;
pbCounter.Value = 0;
btnGenerate.Enabled = false;
try
{
for ( int i = 1; i <= totalRuns; i++ )
{
using (var client = new HttpClient())
await client.PostAsync( "endpoint", new StringContent( JsonConvert.SerializeObject( formContent ), Encoding.UTF8, "application/json" ) );
pbCounter.Value = i;
}
}
catch (Exception ex )
{
MessageBox.Show( ex.Message, "Gift Creator", MessageBoxButtons.OK, MessageBoxIcon.Error );
}
btnGenerate.Enabled = true;
}
因此,此处理程序在等待http请求时将控件返回给调用者(说它过度简化:UI)。请求完成后,继续执行pbCounter.Value = i
行 - 并在UI线程上执行!因此,您可以安全地更新进度条,因为您没有从另一个线程中执行此操作。
我希望这会对你有所帮助。请注意,我将pbCounter.Maximum
设置为您即将运行的循环数,因此您无需计算百分比。