使用 Task.Delay会阻塞当前代码继续执行,但并不会阻塞当前线程执行,在await处,代码执行分为2部分,当前线程转而去执行其他任务,await后的代码可能由新的线程执行,所以不会阻塞当前线程
参考:在Winform开发中,使用Async-Awati异步任务处理代替BackgroundWorker - 伍华聪 - 博客园 (cnblogs.com)
界面提供一个按钮和一个进度条控件,点击后改变进度条进度不会阻塞界面线程,同时使用
Progress类进行进度通知:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
namespace testAsyncAwait
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private async void button1_Click(object sender, EventArgs e)
{
var reporter = new Progress<int>(progressChanged);
var result = await this.WorkStart(reporter);
this.WorkCompleted(result);
}
/// <summary>
/// 任务完成
/// </summary>
/// <param name="result">返回结果CommonResult</param>
void WorkCompleted(CommonResult result)
{
if (result.Success)
{
//操作成功的处理
}
MessageBox.Show("处理完成");
}
/// <summary>
/// 报告进度
/// </summary>
/// <param name="percentage">当前进度</param>
void progressChanged(int percentage)
{
this.progressBar1.Value = percentage;
}
/// <summary>
/// 执行任务
/// </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;
}
}
public class CommonResult
{
public bool Success { get; set; }
public string Message { get; set; }
}
}