异步执行回调

异步执行多个程序,代码如下:

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);

        }
    }

   
}

实际运行画面如下图:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值