// --- 1 普通异步 ---

static void Main(string[] args)

{
DateTime dt = DateTime.Now;

RemoteObj rmtObj = new RemoteObj();
// 1 ---------------------------------------
//Console.WriteLine(rmtObj.Method1(1, 2, 2000));

// 2 ---------------------------------------
MyDelegate md = new MyDelegate(rmtObj.Method1);
IAsyncResult Iar = md.BeginInvoke(33, 12, 5000, null, null);
MainMethod();

if (!Iar.IsCompleted)

{
Iar.AsyncWaitHandle.WaitOne();//因为主方法阻塞3秒,异步方法阻塞2秒,所以这句是不会执行的
}
else

{
Console.WriteLine("结果是" + md.EndInvoke(Iar));
}
Console.WriteLine("用了" + ((TimeSpan)(DateTime.Now - dt)).TotalSeconds + "秒");
Console.ReadLine();
}

//---------------------------------------
public delegate int MyDelegate(int a, int b, int time);

class RemoteObj

{
public RemoteObj()

{
}



/**//// <summary>
/// 返回a+b之和,阻塞milliSecond
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="second"></param>
/// <returns></returns>
public int Method1(int a, int b, int milliSecond)

{
Console.WriteLine("--- 异步方法开始 ---");
System.Threading.Thread.Sleep(milliSecond);
Console.WriteLine("--- 异步方法结束 ---");
return a + b;
}
}

异步的回调
private static MyDelegate md;

// --- 2 回调异步 ---
static void Main(string[] args)

{
DateTime dt = DateTime.Now;
//RemoteObject.MyObject app=(RemoteObject.MyObject)Activator.GetObject(typeof(RemoteObject.MyObject),System.Configuration.ConfigurationSettings.AppSettings["ServiceURL"]);
RemoteObj app = new RemoteObj();
md = new MyDelegate(app.Method1);
AsyncCallback ac = new AsyncCallback(CallBack1);
IAsyncResult Iar = md.BeginInvoke(21, 32, 5000, ac, null);
MainMethod();
Console.WriteLine("用了" + ((TimeSpan)(DateTime.Now - dt)).TotalSeconds + "秒");
Console.ReadLine();
}

public static void CallBack1(IAsyncResult Iar)

{
if (Iar.IsCompleted)

{
Console.WriteLine("结果是" + md.EndInvoke(Iar));
}
}

posted on 2010-12-08 20:48
Victor.Stone 阅读(293)
评论(0) 编辑 收藏 引用 所属分类:
.net framework