当前位置:网站首页>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
边栏推荐
猜你喜欢
随机推荐
Upgrade the smart switch, how much is the difference between the "zero fire version" and "single fire" wiring methods?
SSL证书续费相关问题详解
Summary and sorting of 8 pits of redis distributed lock
Build your own website (15)
2022-07-04:以下go语言代码输出什么?A:true;B:false;C:编译错误。 package main import 'fmt' func
Unity给自己的脚本添加类似编辑器扩展的功能案例ContextMenu的使用
信息学奥赛一本通 1336:【例3-1】找树根和孩子
技术分享 | 接口测试价值与体系
长城证券开户安全吗 买股票怎么开户
关于判断点是否位于轮廓内的一点思考
php伪原创api对接方法
Oracle with as ora-00903: invalid table name multi report error
PolyFit软件介绍
Nebula importer data import practice
偏移量函数及开窗函数
《看完就懂系列》字符串截取方法substr() 、 slice() 和 substring()之间的区别和用法
In flinksql, in addition to data statistics, is the saved data itself a state
LM10丨余弦波动顺势网格策略
如何使用Async-Awati异步任务处理代替BackgroundWorker?
一文掌握数仓中auto analyze的使用