您的位置:首页 > 编程语言 > C#

c# 等待异步委托结果的三种方式

2014-07-26 10:31 495 查看
using System;

using System.Collections.Generic;

using System.Diagnostics;

using System.Linq;

using System.Text;

using System.Threading;

using System.Threading.Tasks;

namespace t_20_01

{

//声明委托类型

public delegate int TakesWhileDelegate(int data,int ms);

class Program

{

static void Main(string[] args)

{

//等待委托的结果

#region 第一种执行操作

TakesWhileDelegate d1=TakesWhile;

//开始一部调用

IAsyncResult ar = d1.BeginInvoke(1, 3000, null, null);

//未完成是的操作

while (!ar.IsCompleted)

{

Console.Write(".");

Thread.Sleep(50);

}

//完成后调用该方法 获取返回结果

int result = d1.EndInvoke(ar);

Console.WriteLine("result:{0}", result);

#endregion

#region 第二种执行操作

TakesWhileDelegate d2 = TakesWhile;

IAsyncResult ar2 = d2.BeginInvoke(1, 3000, null, null);

while (true)

{

Console.Write(".");

// waitone 超时时 循环继续执行

if (ar.AsyncWaitHandle.WaitOne(50, false))

{

Console.WriteLine("can get result now");

break;

}

}

int result2 = d2.EndInvoke(ar2);

Console.WriteLine("result2:{0}",result2);

#endregion

#region 第三种执行操作 回掉函数

TakesWhileDelegate d3 = TakesWhile;

d3.BeginInvoke(1, 3000, TakesAwhileCompleted, d3);

for (int i = 0; i < 100; i++)

{

Console.Write(".{0}",i);

Thread.Sleep(50);

}

#endregion

Console.ReadKey();

}

static void TakesAwhileCompleted(IAsyncResult ar)

{

if (ar == null) throw new ArgumentNullException("ar");

TakesWhileDelegate d3 = ar.AsyncState as TakesWhileDelegate;

Trace.Assert(d3 != null, "Invalid object type");

int result = d3.EndInvoke(ar);

Console.WriteLine("result:{0}",result);

}

static int TakesWhile(int data, int ms)

{

Console.WriteLine("takesAwhile started");

Thread.Sleep(ms);

Console.WriteLine("takesAwhile completed");

return ++data;

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: