异步回调反回直
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace sample
{
class AsyncDemo
{
public string TestMethod(int callDuration, out int threadid)
{
Console.WriteLine("Test Method begins");
Thread.Sleep(callDuration);
threadid = System.Threading.Thread.CurrentThread.ManagedThreadId;
return "MyCallTime was" + callDuration.ToString();
}
}
public delegate string AsyncDelegate(int callDuration, out int threadid);
class Program
{
static void Main(string[] args)
{
int threadID;
AsyncDemo ad = new AsyncDemo();
AsyncDelegate andl = new AsyncDelegate(ad.TestMethod);
IAsyncResult ar = andl.BeginInvoke(3000, out threadID,
new AsyncCallback(CallBackMethod), andl);
Thread.Sleep(10);
Console.WriteLine("Main Thread {0} Does Some Work",
System.Threading.Thread.CurrentThread.ManagedThreadId);
Console.ReadLine();
}
static void CallBackMethod(IAsyncResult ar) //无返回而且只有一个IAsyncResult类型的参数ar
{
int j;
AsyncDelegate andl = (AsyncDelegate)ar.AsyncState;
string a = andl.EndInvoke(out j, ar);//这个是返回值关键
Console.WriteLine(a);
}
}
}