异步调用

因为程序运行速度比较慢,所以要把长时间运行的代码进行异步处理。所以做了一个如下的测试:

ContractedBlock.gifExpandedBlockStart.gifUsing directives#region Using directives
InBlock.gif
InBlock.gif
using System;
InBlock.gif
using System.Collections.Generic;
InBlock.gif
using System.Text;
InBlock.gif
ExpandedBlockEnd.gif
#endregion

None.gif
None.gif
namespace testASycCall
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    
public delegate void AsyncCaller();
InBlock.gif    
class Program
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
void Call0()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            Console.WriteLine(
"Call0:Begin");
InBlock.gif            System.Threading.Thread.Sleep(
2000);
InBlock.gif            Console.WriteLine(
"Call0:End");
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
void Call1()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            Console.WriteLine(
"Call1:Begin");
InBlock.gif            System.Threading.Thread.Sleep(
2000);
InBlock.gif            Console.WriteLine(
"Call1:End");
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif
InBlock.gif        
static void Main(string[] args)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            Program p 
= new Program();
InBlock.gif            Console.WriteLine(
"ready async call0");
InBlock.gif            AsyncCaller ac 
= new AsyncCaller(p.Call0);
InBlock.gif            Console.WriteLine(
"invoke async call0");
InBlock.gif            IAsyncResult ar 
= ac.BeginInvoke(nullnull);
InBlock.gif            Console.WriteLine(
"call call1");
InBlock.gif            p.Call1();
InBlock.gif            Console.WriteLine(
"call1 end");
InBlock.gif            Console.WriteLine(
"wait call 0 end");
InBlock.gif            ar.AsyncWaitHandle.WaitOne();
InBlock.gif            Console.WriteLine(
"call 0 end");
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif


程序运行结果如下:

ready async call0
invoke async call0
call call1
Call0:Begin
Call1:Begin
Call0:End
Call1:End
call1 end
wait call 0 end
call 0 end

看起来并行的还比较明显emteeth.gif!

相同的例子在MSDN上面也有,如果你机器上装了MSDN的话,可以到这里看到原文。不过俺的例子好像比它的更明显些emwink.gif

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值