Func<
int
,
int
> mySum1 =
SumNumbers;
Func
<
int
,
int
> mySum2 =
SumNumbers;
Func
<
int
,
int
> mySum3 =
SumNumbers;
AsyncCallback callback
= c => Console.WriteLine(
"
线程ID:{0},回调函数执行:{1}
"
,Thread.CurrentThread.ManagedThreadId,c.AsyncState);
IAsyncResult result1
= mySum1.BeginInvoke(
10000
, callback,
"
第一个异步
"
);
IAsyncResult result2
= mySum2.BeginInvoke(
10000
, callback,
"
第二个异步
"
);
IAsyncResult result3
= mySum3.BeginInvoke(
10000
, callback,
"
第三个异步
"
);
//
异步等待方式1:使用EndInvoke
int
asyc1 =
mySum1.EndInvoke(result1);
Console.WriteLine(
"
第一个异步已经执行完成,结果:{0}
"
,asyc1);
//
异步等待方式2:使用AsyncWaitHandle.WaitOne,参数-1表示一直等待到执行完成
if
(result2.AsyncWaitHandle.WaitOne(-
1
))
Console.WriteLine(
"
第二个异步执行完成
"
);
//
异步等待方式3:使用IsCompleted判断
while
(!
result3.IsCompleted)
Console.WriteLine(
"
第三个异步还在执行中....
"
);
Thread.Sleep(
300
);
Console.WriteLine(
"
第三个异步执行完成
"
);
Console.ReadKey();
public
static
int
SumNumbers(
int
count)
int
sum =
0
;
for
(
int
i =
0
; i < count; i++
)
sum
+=
i;
Thread.Sleep(
3000
);
return
sum;
2. 代码执行结果: