111,092
社区成员




public delegate int AddDelegate(int x,int y);
class Program
{
static void Main(string[] args)
{
Console.WriteLine("客户端应用程序开始运行......");
Thread.CurrentThread.Name = "主线程";
Calculator cal = new Calculator();
AddDelegate del = new AddDelegate(cal.Add);
AsyncCallback callback = new AsyncCallback(OnAddComplete);
string data = "hello,everybody";
del.BeginInvoke(2, 3, callback, data);//异步调用方法
for (int i = 0; i < 3; i++)
{
Thread.Sleep(1000);
Console.WriteLine("{0}:执行{1}秒了!",Thread.CurrentThread.Name ,i);
}
Console.WriteLine("完成");
Console.ReadKey();
}
public static void OnAddComplete(IAsyncResult asyncResult)
{
AsyncResult result = (AsyncResult)asyncResult;
AddDelegate del = (AddDelegate)result.AsyncDelegate;
string data = (string)asyncResult.AsyncState;
int rtn = del.EndInvoke(asyncResult);
Console.WriteLine("计算结果为:{0},data:{1}", rtn,data);
}
}
public class Calculator
{
public int Add(int x,int y)
{
if (Thread.CurrentThread.IsThreadPoolThread)
{
Thread.CurrentThread.Name = "Pool Thread";
}
Console.WriteLine("方法调用开始");
for (int i = 0; i < 2; i++)
{
Thread.Sleep(1000);
Console.WriteLine("{0}:正在计算中......", Thread.CurrentThread.Name);
}
Console.WriteLine("方法计算完毕");
return x + y;
}
}