其他分享
首页 > 其他分享> > IAsyncResult

IAsyncResult

作者:互联网

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace asyncApp
{
    public partial class FrmAsync : Form
    {
        public FrmAsync()
        {
            InitializeComponent();
        }
        public int ExecuteTask1(int num)
        {
            Thread.Sleep(5000);
            return num * num;
        }
        public int ExecuteTask2(int num)
        {
            return num * num;
        }
        private void btnExectue1_Click(object sender, EventArgs e)
        {
            this.lblCount1.Text = ExecuteTask1(10).ToString();
            this.lblCount2.Text = ExecuteTask2(10).ToString();
        }

        private void btnExecute2_Click(object sender, EventArgs e)
        {
            MyDelegate dete = ExecuteTask1;
            //异步操作执行状态借口
            IAsyncResult result = dete.BeginInvoke(10,null,null);
            this.lblCount1.Text = "正在计算......";
            this.lblCount2.Text = ExecuteTask2(10).ToString();
            //EndInvoke方法借助IAsyncResult借口对象,不断地查询异步调用是否结束;
            //该方法知道异步调用的方法所有参数,所以异步调用完毕以后,取出异步调用结果作为返回值
            int res = dete.EndInvoke(result);
            this.lblCount1.Text = res.ToString();
        }
        public delegate int MyDelegate(int num);
    }
}

  

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace asyncAppCallback
{
    public partial class FrmAppCallback : Form
    {
        public FrmAppCallback()
        {
            InitializeComponent();
            this.objCal = new MyDelegate(ExecuteTask);//初始化成员变量
            //this.objCal = (num, ms)=>
            //{
            //    Thread.Sleep(ms);
            //    return num * num;
            //};

        }
        //【1】声明一个委托
        public delegate int MyDelegate(int num, int ms);
        //【2】根据委托声明一个方法 
        private int ExecuteTask(int num, int ms)
        {
            Thread.Sleep(ms);
            return num * num;
        }
        //【3】创建委托变量
        MyDelegate objCal = null;//ExecuteTask;
        //【4】同步执行多个任务
        private void btnExecu_Click(object sender, EventArgs e)
        {
            for (int i = 1; i <= 10; i++)
            {
                objCal.BeginInvoke(10 * i, 1000 * i, MyCallback,i);
            }
        }
        //【5】创建回调函数
        private void MyCallback(IAsyncResult result)
        {
           int res= objCal.EndInvoke(result);
            //异步显示结果
            Console.WriteLine("第{0}个计算结果:{1}",result.AsyncState,res);
        }
    }
}

  

标签:int,Text,System,num,IAsyncResult,using,public
来源: https://www.cnblogs.com/Jeely/p/11001987.html