当前位置:网站首页>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
边栏推荐
- Unity编辑器扩展C#遍历文件夹以及子目录下的所有图片
- 生成XML元素
- 如何使用Async-Awati异步任务处理代替BackgroundWorker?
- 技术分享 | 接口测试价值与体系
- From automation to digital twins, what can Tupo do?
- prometheus安装
- 指定输出的字符集
- 2019年蜀山区第十五届青少年信息学竞赛
- The page element is vertically and horizontally centered, realizing the vertical and horizontal centering of known or unknown width.
- 其他InterSystems %Net工具
猜你喜欢
随机推荐
安徽 中安在线文旅频道推出“跟着小编游安徽”系列融媒体产品
LeetCode第300场周赛(20220703)
Pytest 可视化测试报告之 Allure
测试工程师如何“攻城”(下)
LeetCode 赎金信 C#解答
大div中有多个div,这些div在同一行显示,溢出后产生滚动条而不换行
6.26cf simulation match B: solution to array reduction problem
Shell programming core technology "three"
从实时应用角度谈通信总线仲裁机制和网络流控
Learning path PHP -- phpstudy "hosts file does not exist or is blocked from opening" when creating the project
生成XML元素
Wireshark网络抓包
小发猫物联网平台搭建与应用模型
Bi skills - permission axis
Process of manually encrypt the mass-producing firmware and programming ESP devices
反射(一)
资料下载 丨首届腾讯技术开放日课程精华!
The page element is vertically and horizontally centered, realizing the vertical and horizontal centering of known or unknown width.
函数式接口
876. Intermediate node of linked list