版权声明:本人菜鸟一只,如文章有错误或您有高见,请不吝赐教 https://blog.csdn.net/qq_41138935/article/details/82847119
定义委托 :TakesAWhileDelegate 引用TakesAWhile方法。
IAsyncResult表示异步操作的状态,BeginInvoke
方法是使用委托来以异步方式调用的方法,
返回类型是IAsyncResult,方法IsCompleted验证该委托是否完成了任务。只要委托没有完成任务,程序的主线程就继续执行while循环。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp7控制台
{
public delegate int TakesAWhileDelegate(int data,int ms);
class Program
{
static int TakesAWhile(int data,int ms)
{
Console.WriteLine("TakesAWhile started");
System.Threading.Thread.Sleep(ms);
Console.WriteLine("TakesAWhile comleted");
return ++data;
}
static void Main(string[] args)
{
TakesAWhileDelegate dl = TakesAWhile;
IAsyncResult ar = dl.BeginInvoke(1, 3000, null, null);
while (!ar.IsCompleted)
{
Console.Write(",");
System.Threading.Thread.Sleep(50);
}
int result = dl.EndInvoke(ar);
Console.WriteLine("result:{0}",result);
Console.ReadKey();
}
}
}