当前位置:网站首页>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
边栏推荐
- 一文掌握数仓中auto analyze的使用
- The 15th youth informatics competition in Shushan District in 2019
- 指定输出的字符集
- [uniapp] uniapp development app online Preview PDF file
- 神经网络物联网是什么意思通俗的解释
- 在线文本行固定长度填充工具
- 升级智能开关,“零火版”、“单火”接线方式差异有多大?
- 2022CoCa: Contrastive Captioners are Image-Text Fountion Models
- Upgrade the smart switch, how much is the difference between the "zero fire version" and "single fire" wiring methods?
- Lex and yacc based lexical analyzer + parser
猜你喜欢

OpenCV的二值化处理函数threshold()详解

英特尔集成光电研究最新进展推动共封装光学和光互连技术进步

“只跑一趟”,小区装维任务主动推荐探索

联想首次详解绿色智城数字孪生平台 破解城市双碳升级难点

Oracle with as ORA-00903: invalid table name 多表报错

2022CoCa: Contrastive Captioners are Image-Text Fountion Models

MySQL数据库基本操作-DDL | 黑马程序员

如何使用Async-Awati异步任务处理代替BackgroundWorker?

建立自己的网站(15)

在线SQL转Excel(xls/xlsx)工具
随机推荐
There are multiple divs in the large div, which are displayed on the same line. After overflow, scroll bars are generated without line breaks
Go microservice (II) - detailed introduction to protobuf
How test engineers "attack the city" (Part 2)
爬虫(6) - 网页数据解析(2) | BeautifulSoup4在爬虫中的使用
安徽 中安在线文旅频道推出“跟着小编游安徽”系列融媒体产品
更安全、更智能、更精致,长安Lumin完虐宏光MINI EV?
YOLOv5s-ShuffleNetV2
Torchdrug tutorial
[opencv introduction to mastery 9] opencv video capture, image and video conversion
Perfect JS event delegation
偏移量函数及开窗函数
请教一下 flinksql中 除了数据统计结果是状态被保存 数据本身也是状态吗
DeFi生态NFT流动性挖矿系统开发搭建
在线文本行固定长度填充工具
Qt实现界面滑动切换效果
SSL证书续费相关问题详解
redis分布式锁的8大坑总结梳理
6.26cf simulation race e: solution to the problem of price maximization
Process of manually encrypt the mass-producing firmware and programming ESP devices
Build your own website (15)