小窗体实现异步编程
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;
namespace AsyncDemo
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
}
private void btnExe1_Click(object sender, EventArgs e)
{
this.lblCount1.Text = ExectuteTask1(10).ToString();
this.lblCount2.Text = ExectuteTask2(10).ToString();
}
// 2、根据委托定义实现方法
private int ExectuteTask1(int num)
{
System.Threading.Thread.Sleep(5000); // 延迟5000ms
return num * num;
}
private int ExectuteTask2(int num)
{
return num * num;
}
// 3、异步调用
private void btnExe2_Click(object sender, EventArgs e)
{
MyCalculator objMycal = ExectuteTask1;//创建委托变量并代表方法1
// 异步调用任务
IAsyncResult result = objMycal.BeginInvoke(10,null,null);
this.lblCount1.Text = "正在计算,请稍等...";
// 同时执行其他任务
this.lblCount2.Text = ExectuteTask2(10).ToString();
// 获取异步计算结果
int res = objMycal.EndInvoke(result);
this.lblCount1.Text = res.ToString();
}
}
// 1、定义委托
public delegate int MyCalculator(int num);
}
界面如下图所示: