赤道上的小熊又来了,在开发过程中,如果有一个方法比较耗时,又想获得该方法执行完后的结果,可以使用一个超级简单的方式,那就是基于委托的异步编程,异步方式理论上属于多线程,在执行时每个方法都会重新开启一个新的线程,话不多说直接上例子
public delegate string MyDelegate(int arg); //【1】声明一个委托变量
MyDelegate dele = null; //【2】定义一个委托
public Class1()
{
dele = new MyDelegate(Myfuntion2);//【3】将委托与执行方法关联
}
public void Exe()
{
for (int i = 1; i < 10; i++)
{
//使用委托的BeginInvoke 开启异步操作 (输入参数(委托有几个参数,该处就有几个参数);回调函数;回调函数的参数)
IAsyncResult result = dele.BeginInvoke(10 * i, callBackMethod, i);
}
Console.ReadKey();
}
private string Myfuntion2(int i) //执行的方法
{
try
{
System.Threading.Thread.Sleep(5000);//延时5秒
return ((i+1).ToString());
}
catch (Exception)
{
return "异常";
}
}
private void callBackMethod(IAsyncResult ar) //【4】回调函数
{
// MyDelegate caller = ar.AsyncState as MyDelegate;
try
{
string res = dele.EndInvoke(ar); //执行方法的返回值 Myfuntion2的返回值
string result = ar.AsyncState.ToString(); //回调函数的输入参数
Console.WriteLine("线程ID "+Thread.CurrentThread.ManagedThreadId+" 回调函数结果:"+ res);
//如果为窗体时可采用下列方法将结果返回到窗体
// richTextBox1.Invoke(new Action<string>(s => { richTextBox1.Text = richTextBox1.Text + s + "\n"; }), "线程:" + Thread.CurrentThread.ManagedThreadId);
// richTextBox1.Invoke(new Action<string>(s => { richTextBox1.Text = richTextBox1.Text + s + "\n"; }), result);
if (res == "异常")
{
string result11 = ar.AsyncState.ToString();
}
}
catch (Exception ex)
{
string result = ar.AsyncState.ToString();
}
}