编程语言
首页 > 编程语言> > c# 异步编程 使用回调函数例子

c# 异步编程 使用回调函数例子

作者:互联网

环境VS2010,

在项目属性中输出类型选择控制台应用程序

 

 

运行结果

 

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

namespace _02_AsyncCallbackDemo
{
public partial class Form1 : Form
{
//3.声明一个全局委托变量
MyDel mydel = null;
public Form1()
{
InitializeComponent();
//4.实例化委托
mydel = MyExecute;

}

private void button1_Click(object sender, EventArgs e)
{
for(int i=1;i<11;i++)
{//5.通过mydel 委托异步执行十次方法,每个方法结束都通过他的回调函数返回结果
mydel.BeginInvoke(10 * i, 1000 *i, MyCallback, i);
}

}

//1.定义一个委托
public delegate int MyDel(int num,int ms);
//2.根据委托定义方法
private int MyExecute(int num, int ms)
{
System.Threading.Thread.Sleep(ms);
return num * num;
}
//6.定义方法的回调函数,注意回调函数其实也是一个方法,他没有返回值类型,
private void MyCallback(IAsyncResult result)
{
int res = mydel.EndInvoke(result);
Console.WriteLine("第{0}个计算结果是:{1}", result.AsyncState.ToString(), res);
}
}
}

标签:异步,c#,编程,System,int,num,mydel,using,public
来源: https://www.cnblogs.com/arcticfish/p/10862055.html