例子1:
using System;
class Program
{
public delegate int CalculateDelegate(int min,int max);
static void Main(string[] args)
{
CalculateDelegate d = Calculate;
//为了简单,未检查输入是否数字
Console.WriteLine("请输入最小数字:");
int min = int.Parse(Console.ReadLine());
Console.WriteLine("请输入最大数字:");
int max = int.Parse(Console.ReadLine());
//public IAsyncResult BeginInvoke(
// <输入和输出变量>,
// AsyncCallback callback, object asyncState
//)
//第一部分是定义委托时确定的方法签名中的参数列表,没有参数时为空d.BeginInvoke(null, null);
//第二个参数callback是当异步调用结束时自动回调的函数
//第三个参数asyncState用于向第二个参数所确定的callback回调函数提供额外的信息
IAsyncResult ret = d.BeginInvoke(min, max, null, null);
Console.WriteLine("正在计算中,请耐心等待.....");
while (!ret.IsCompleted)
{
Console.Write(".");
System.Threading.Thread.Sleep(1000);
}
int count = d.EndInvoke(ret);
Console.WriteLine("/n计算完成。从{0}加到{1}的值为:{2}", min, max, count);
Console.ReadKey();
}
static int Calculate(int min,int max)
{
int count = 0;
for (int i = min; i < max; i++)
{
count += i;
}
return count;
}
}
例子2:
例子1使用轮询方法不断询问异步调用是否完成,会浪费不少CPU时间在循环等待上,可以让异步调用方法在结束时自动调用一个函数,并在这个函数中显示处理结果。
using System;
class Program
{
public delegate int CalculateDelegate(int min, int max);
private static CalculateDelegate d = new CalculateDelegate(Calculate);
static void Main(string[] args)
{
Console.WriteLine("请输入最小数字:");
int min = int.Parse(Console.ReadLine());
Console.WriteLine("请输入最大数字:");
int max = int.Parse(Console.ReadLine());
//BeginInvoke()方法的第二个参数指定当异步调用结束时回调ShowMsg(),第三个参数传送给回调函数
IAsyncResult ret = d.BeginInvoke(min, max, ShowMsg, (min + "," + max));
Console.ReadKey();
}
static int Calculate(int min, int max)
{
int count = 0;
for (int i = min; i < max; i++)
{
count += i;
}
return count;
}
static void ShowMsg(IAsyncResult result)
{
int count = d.EndInvoke(result);
string[] n = ((string)result.AsyncState).Split(',');
Console.WriteLine("从{0}加到{1}的和是{2}。", n[0], n[1], count);
}
}