异步执行多个程序,代码如下:
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 _02_AsyncCallbackDemo
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
// 3、初始化委托变量
this.objMycal = new MyCalculator(ExecuteTask);
// 将 2+3 步合并
//this.objMycal = (num, ms) =>
// {
// System.Threading.Thread.Sleep(ms);
// return num * num;
// };
}
// 1、申明一个委托
public delegate int MyCalculator(int num, int ms);
//2、根据委托定义方法:返回一个数的平方
private int ExecuteTask(int num,int ms)
{
System.Threading.Thread.Sleep(ms);
return num * num;
}
// 3、创建委托变量
MyCalculator objMycal = null;
// 同步执行多个任务
private void btnExec_Click(object sender, EventArgs e)
{
for (int i = 0; i < 11; i++) // 产生10个任务
{
//开始异步执行,并封装回调函数
objMycal.BeginInvoke(10*i,1000*i,MyCallback,i);
// 最后一个参数i给回调函数的字段AsyncState赋值,这个字段是object类型,如果数据很多可以传递集合或者类、结构都可以
}
}
// 5、回调函数
private void MyCallback(IAsyncResult result)
{
int res = objMycal.EndInvoke(result);
// 异步显示结果形式:
Console.WriteLine("第{0}个计算结果为:{1}",result.AsyncState.ToString(),res);
}
}
}
实际运行画面如下图:

博客展示了异步执行多个程序的代码,还给出了实际运行画面。聚焦于信息技术中程序异步执行相关内容。
524

被折叠的 条评论
为什么被折叠?



