我创建的是一个winform测试项目:界面如下:
设置:
下面是代码:
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 AsyncCallbackDemo { public partial class Form1 : Form { public Form1() { InitializeComponent(); objMyCal = ExecuteTask; } //定义一个委托 public delegate int MyCalculator(int num,int ms); //根据委托定义方法,返回一个数的平方 private int ExecuteTask(int num,int ms) { Thread.Sleep(ms); return num * num; } MyCalculator objMyCal = null; private void button1_Click(object sender, EventArgs e) { for (int i = 0; i < 11; i++) { //定义回调函数MyCallBack,传入回调值i objMyCal.BeginInvoke(10 * i,1000*1, MyCallBack, i); } } private void MyCallBack(IAsyncResult result) { //返回结果 int res = objMyCal.EndInvoke(result); Console.WriteLine("第{0}个计算结果为{1}",result.AsyncState.ToString(),res); } } }
原文地址:https://www.cnblogs.com/dearbeans/p/9349724.html
时间: 2024-10-12 07:30:26