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

C#中一个异步回调的实例

2016-09-26 09:08 211 查看
namespace 委托_异步_回调
{
class Program
{
//创建委托,并实例化一个方法
public delegate string MyDelegate(object data);
private MyDelegate mydelegate = null;
static void Main(string[] args)
{
//开始异步执行
mydelegate =new MyDelegate(TestMethod);
IAsyncResult result = mydelegate.BeginInvoke("Thread Param", TestCallback, null);
//判断是否执行完成
Console.Write("请稍等");
while (!result.AsyncWaitHandle.WaitOne(100))
{
Console.Write(".");
}

Console.ReadLine();
}

//线程函数,即异步执行的程序
public string TestMethod(object data)
{
string datastr = data.ToString();
System.Threading.Thread.Sleep(1000);
return datastr;
}

//异步回调函数,异步执行完成以后需要返回的数据
public void TestCallback(IAsyncResult data)
{
//datastr,异步回调最终得到的数据,也就是异步执行程序执行完了以后的返回值
//data,异步回调的对象,也是传入回调函数的一个数据,可以用来和返回值进行相关操作
string datastr=mydelegate.EndInvoke(data);
Console.WriteLine("\n"+datastr);
}

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