当前位置:网站首页>How to use async Awati asynchronous task processing instead of backgroundworker?
How to use async Awati asynchronous task processing instead of backgroundworker?
2022-07-04 19:29:00 【Interface development Starling】
stay WinForm Sometimes in the development, we want to not affect the main UI Processing of threads , We used to use background threads BackgroundWorker To handle some task operations , But with the convenience of asynchronous processing , We can use Async-Awati Asynchronous task processing replaces the original background thread BackgroundWorker Processing mode , More concise and clear .
In some time-consuming operations , Long run time may result in a user interface (UI) In stop response state , So use Async-Awati Asynchronous task processing or background thread BackgroundWorker It is necessary to handle some task operations .
In the use of BackgroundWorker In the process of , We can define our own state parameter information , So as to realize the real-time tracking of thread status, progress and information prompt , It is convenient for us to inform in time UI updated .
Now use Async-Awati Asynchronous task processing , Can also be notified during processing UI Update progress and tips .
Click to get DevExpress Winformv21.2 Official version
1. review BackgroundWorker Processing code of background thread
So let's see BackgroundWorker Operation code of background thread , Compare and then introduce the use of Async-Awati Asynchronous task processing and notification operations .
Generally, the code needs to initialize the background thread object , As shown in the following code .
public partial class MainFrame : BaseForm
{
/// <summary>
/// Add a variable to record thread status
/// </summary>
private bool IsThreadRunning = false;
private BackgroundWorker worker = new BackgroundWorker();
public MainFrame()
{
InitializeComponent();
Portal.gc.InitData();
worker.WorkerSupportsCancellation = true; // Support cancellation
worker.WorkerReportsProgress = true; // Support for reporting progress
worker.DoWork += worker_DoWork; // Treatment process
worker.RunWorkerCompleted += worker_RunWorkerCompleted; // To complete the operation
worker.ProgressChanged += worker_ProgressChanged; // Reporting progress
}
For example, notification of progress bar , The main task is to calculate the total number of tasks , It is also used to display the current task progress information , The example code is as follows :
/// <summary>
/// Notification of progress bar
/// </summary>
void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.barProgress.EditValue = e.ProgressPercentage;
CollectStateInfo stateInfo = e.UserState as CollectStateInfo;
if (stateInfo != null)
{
var message = string.Format(" Collecting {0} Of {1} , Project name: :{2}", stateInfo.TotalRecords, stateInfo.CompletedRecord + 1, stateInfo.CurrentItemName);
this.lblTips.Text = message;
this.barTips.Caption = message;
// Record the operating position
JobParameterHelper.SaveData(new CurrentJobParameter(stateInfo));
}
}
The key event handled by the background process is the code implementation of the process , When it deals with tasks , Notify the current status by means of events UI Show .
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
Random r = new Random();
int numCount = 0;
while (worker.CancellationPending == false)
{
int num = r.Next(0, 10000);
if (num % 5 == 0)
{
numCount++;
worker.ReportProgress(0, num);
Thread.Sleep(1000);
}
}
e.Result = numCount;
}
When the trigger task starts , Our calling code is as follows .
if (!worker.IsBusy)
{
worker.RunWorkerAsync(stateInfo);
}
When the task is completed , Notify the update interface .
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// Restore button status
InitCollectState();
IsThreadRunning = false;
string message = " Acquisition operation completed ";
MessageDxUtil.ShowTips(message);
}
2. Use Async-Awati Asynchronous task processing replaces BackgroundWorker
For testing, use Asyn-Await Asynchronous processing , I created a simple Demo Program , Used to test its effect .
Put a button inside the window , Trigger button to execute task operation , And prompt the progress bar information step by step , Prompt task completion after completion .
To prompt progress information in asynchronous processing , We introduced Progress Thread notification object .

Define a thread notification Progress object , As shown below . there int You can also change to a custom object class , So as to carry more information .
var reporter = new Progress<int>(progressChanged);
among progressChanged Is a notification we define UI Handler to display progress , As shown below .
/// <summary>
/// Reporting progress
/// </summary>
/// <param name="percentage"> Current progress </param>
void progressChanged(int percentage)
{
this.progressBar1.EditValue = percentage;
this.progressPanel.Caption = percentage == 100 ? " The task has been completed ": " The task is being processed ";
this.progressPanel.Description = String.Format(" complete 【{0}%】", percentage);
}
Then we define a task - handling WorkStart Method , Receive one Progress object , As shown in the following code .
var reporter = new Progress<int>(progressChanged);
var result = await this.WorkStart(reporter);
Call asynchronously for simple style , We are just delaying the task here , If actually handled , Call the asynchronous method .
/// <summary>
/// Perform tasks
/// </summary>
private async Task<CommonResult> WorkStart(IProgress<int> progress)
{
var result = new CommonResult();
for(int i = 0; i < 100; i++)
{
await Task.Delay(100);
progress.Report(i + 1);
}
result.Success = true;
return result;
}
We can see , Tasks are executed to one node at a time , Object methods will be called Report Conduct notification processing .
When the task is completed , We can simply handle the notification . The whole code is as follows .
/// <summary>
/// Async Await Asynchronous thread processing
/// </summary>
public partial class FrmAsyncAwaitDemo : DevExpress.XtraEditors.XtraForm
{
public FrmAsyncAwaitDemo()
{
InitializeComponent();
this.progressBar1.Visible = false;
this.progressPanel.Visible = false;
}
private async void btnStart_Click(object sender, EventArgs e)
{
this.btnStart.Enabled = false;
this.progressBar1.Visible = true;
this.progressPanel.Visible = true;
var reporter = new Progress<int>(progressChanged);
var result = await this.WorkStart(reporter);
this.WorkCompleted(result);
}
/// <summary>
/// Task to complete
/// </summary>
/// <param name="result"> Return results CommonResult</param>
void WorkCompleted(CommonResult result)
{
if (result.Success)
{
// Successful operation processing
}
var alert = new AlertControl();
alert.FormLocation = AlertFormLocation.TopRight;
alert.AutoFormDelay = 2000;
alert.Show(this, " Task Tips ", result.Success ? " Task processing completed , Successful operation " : result.ErrorMessage);
this.progressBar1.Visible = false;
this.progressPanel.Visible = false;
this.btnStart.Enabled = true;
}
/// <summary>
/// Reporting progress
/// </summary>
/// <param name="percentage"> Current progress </param>
void progressChanged(int percentage)
{
this.progressBar1.EditValue = percentage;
this.progressPanel.Caption = percentage == 100 ? " The task has been completed ": " The task is being processed ";
this.progressPanel.Description = String.Format(" complete 【{0}%】", percentage);
}
/// <summary>
/// Perform tasks
/// </summary>
private async Task<CommonResult> WorkStart(IProgress<int> progress)
{
var result = new CommonResult();
for(int i = 0; i < 100; i++)
{
await Task.Delay(100);
progress.Report(i + 1);
}
result.Success = true;
return result;
}
}
In our actual case , File upload processing uses this method to notify UI Threads , The code for task processing is as follows .

Therefore use Async-Awati Asynchronous task processing replaces BackgroundWorker, Simpler code , And use IProgress Interface classes to handle notifications , It's also very convenient .
DevExpress WinForm | Download trial
DevExpress WinForm Have 180+ Components and UI library , for Windows Forms Platform to create influential business solutions .DevExpress WinForms It can perfectly build fluency 、 Beautiful and easy to use applications , Whether it's Office Style interface , Or analyze and process a large number of business data , It can be easily competent !
Reprinted from : Blog Garden - Wu Huacong
DevExpress Technology exchange group 6:600715373 Welcome to group discussion
边栏推荐
- 资料下载 丨首届腾讯技术开放日课程精华!
- Technology sharing | interface testing value and system
- Lm10 cosine wave homeopathic grid strategy
- Detailed explanation of issues related to SSL certificate renewal
- A method of using tree LSTM reinforcement learning for connection sequence selection
- 2014合肥市第三十一届青少年信息学奥林匹克竞赛(小学组)试题
- 页面元素垂直水平居中、实现已知或者未知宽度的垂直水平居中。
- FPGA时序约束分享01_四大步骤简述
- 模板_判断素数_开方 / 六素数法
- QT realizes interface sliding switching effect
猜你喜欢
与二值化阈值处理相关的OpenCV函数、方法汇总,便于对比和拿来使用
MySQL数据库基本操作-DDL | 黑马程序员
Use canal and rocketmq to listen to MySQL binlog logs
读写关闭的channel是啥后果?
Nebula importer data import practice
Process of manually encrypt the mass-producing firmware and programming ESP devices
Torchdrug tutorial
node_exporter部署
Rookie post station management system based on C language
奥迪AUDI EDI INVOIC发票报文详解
随机推荐
与二值化阈值处理相关的OpenCV函数、方法汇总,便于对比和拿来使用
Have you guys ever used CDC direct Mysql to Clickhouse
Upgrade the smart switch, how much is the difference between the "zero fire version" and "single fire" wiring methods?
Caché WebSocket
A method of using tree LSTM reinforcement learning for connection sequence selection
6.26cf simulation match B: solution to array reduction problem
建立自己的网站(15)
Unity editor extends C to traverse all pictures in folders and subdirectories
更安全、更智能、更精致,长安Lumin完虐宏光MINI EV?
使用SSH
Caché WebSocket
QT realizes interface sliding switching effect
关于判断点是否位于轮廓内的一点思考
Li Chi's work and life summary in June 2022
自由小兵儿
sqlserver的CDC第一次查询的能读取到数据,但后面增删改读取不到,是什么原因
[发布] 一个测试 WebService 和数据库连接的工具 - DBTest v1.0
MySQL数据库基本操作-DDL | 黑马程序员
测试工程师如何“攻城”(下)
2022CoCa: Contrastive Captioners are Image-Text Fountion Models