概述
1.等待句柄
IAsyncResult ar = fu.BeginInvoke(1, 2, null , null);
2.回调
IAsyncResult ar = fu.BeginInvoke(1, 2, fCompleted, fu);
public static void fCompleted(IAsyncResult ar) {
Console.WriteLine(“fCompleted”);
}
c#-异步委托
using System;
using System.Threading;
// c#-异步委托
namespace ConsoleApp13
{
public delegate int dfun(int a, int b);
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
main1();
//main2();
//main3();
//main4();
}
// 异步委托
static void main1() {
dfun fu = fun;
IAsyncResult ar = fu.BeginInvoke(1, 2, null , null);
while (!ar.IsCompleted)
{
Console.WriteLine(".");
System.Threading.Thread.Sleep(50);
}
int result = fu.EndInvoke(ar);
Console.WriteLine("result:{0}", result);
}
// 等待句柄
static void main2() {
dfun fu = fun;
IAsyncResult ar = fu.BeginInvoke(1, 2, null , null);
while (!ar.IsCompleted)
{
Console.WriteLine(".");
if (ar.AsyncWaitHandle.WaitOne(50, false)) {
break;
}
}
int result = fu.EndInvoke(ar);
Console.WriteLine("result:{0}", result);
}
// 异步回调
static void main3() {
dfun fu = fun;
IAsyncResult ar = fu.BeginInvoke(1, 2, fCompleted, fu);
for (int i = 0; i < 100; i++) {
Console.Write(".");
Thread.Sleep(50);
}
}
// 使用lambda
static void main4() {
dfun fu = fun;
fu.BeginInvoke(1,2,
ar => {
int result = fu.EndInvoke(ar);
Console.WriteLine("result:{0}", result);
}, null);
for (int i = 0; i < 100; i++) {
Console.Write(".");
Thread.Sleep(50);
}
}
public static int fun(int a, int b) {
Console.WriteLine("fun start");
Thread.Sleep(500);
Console.WriteLine("fun end");
return a + b;
}
public static void fCompleted(IAsyncResult ar) {
Console.WriteLine("fCompleted");
}
}
}
等待句柄
异步回调
使用lambda