异步调用

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

Using directives

namespace testASycCall
{
    
public delegate void AsyncCaller();
    
class Program
    
{
        
void Call0()
        
{
            Console.WriteLine(
"Call0:Begin");
            System.Threading.Thread.Sleep(
2000);
            Console.WriteLine(
"Call0:End");
        }


        
void Call1()
        
{
            Console.WriteLine(
"Call1:Begin");
            System.Threading.Thread.Sleep(
2000);
            Console.WriteLine(
"Call1:End");
        }



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

    }

}


程序运行结果如下:

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

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

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

 

 

posted on   老翅寒暑  阅读(1066)  评论(3编辑  收藏  举报

编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了

导航

< 2004年11月 >
31 1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 1 2 3 4
5 6 7 8 9 10 11
点击右上角即可分享
微信分享提示