前言

新进阶的程序员可能对async、await用得比较多,却对之前的异步了解甚少。本人就是此类,因此打算回顾学习下异步的进化史。

本文主要是回顾async异步模式之前的异步,下篇文章再来重点分析async异步模式。

apm

apm 异步编程模型,asynchronous programming model

早在c#1的时候就有了apm。虽然不是很熟悉,但是多少还是见过的。就是那些类是beginxxx和endxxx的方法,且beginxxx返回值是iasyncresult接口。

在正式写apm示例之前我们先给出一段同步代码:

//1、同步方法
private void button1_click(object sender, eventargs e)
{          
    debug.writeline("【debug】线程id:" + thread.currentthread.managedthreadid);

    var request = webrequest.create("https://github.com/");//为了更好的演示效果,我们使用网速比较慢的外网
    request.getresponse();//发送请求    

    debug.writeline("【debug】线程id:" + thread.currentthread.managedthreadid);
    label1.text = "执行完毕!";
}

【说明】为了更好的演示异步效果,这里我们使用winform程序来做示例。(因为winform始终都需要ui线程渲染界面,如果被ui线程占用则会出现“假死”状态)

【效果图】

看图得知:

我们在执行方法的时候页面出现了“假死”,拖不动了。

我们看到打印结果,方法调用前和调用后线程id都是9(也就是同一个线程)

下面我们再来演示对应的异步方法:(begingetresponse、endgetresponse所谓的apm异步模型)

private void button2_click(object sender, eventargs e)
{
    //1、apm 异步编程模型,asynchronous programming model
    //c#1[基于iasyncresult接口实现beginxxx和endxxx的方法]             
    debug.writeline("【debug】主线程id:" + thread.currentthread.managedthreadid);

    var request = webrequest.create("https://github.com/");
    request.begingetresponse(new asynccallback(t =>//执行完成后的回调
    {
        var response = request.endgetresponse(t);
        var stream = response.getresponsestream();//获取返回数据流 

        using (streamreader reader = new streamreader(stream))
        {
            stringbuilder sb = new stringbuilder();
            while (!reader.endofstream)
            {
                var content = reader.readline();
                sb.append(content);
            }
            debug.writeline("【debug】" + sb.tostring().trim().substring(0, 100) + "...");//只取返回内容的前100个字符 
            debug.writeline("【debug】异步线程id:" + thread.currentthread.managedthreadid);
            label1.invoke((action)(() => { label1.text = "执行完毕!"; }));//这里跨线程访问ui需要做处理
        }
    }), null);

    debug.writeline("【debug】主线程id:" + thread.currentthread.managedthreadid); 
}

【效果图】

看图得知:

  • 启用异步方法并没有是ui界面卡死
  • 异步方法启动了另外一个id为12的线程

上面代码执行顺序:

前面我们说过,apm的bebinxxx必须返回iasyncresult接口。那么接下来我们分析iasyncresult接口:

首先我们看:

确实返回的是iasyncresult接口。那iasyncresult到底长的什么样子?:

并没有想象中的那么复杂嘛。我们是否可以尝试这实现这个接口,然后显示自己的异步方法呢?

首先定一个类mywebrequest,然后继承iasyncresult:(下面是基本的伪代码实现)

public class mywebrequest : iasyncresult
{
    public object asyncstate
    {
        get { throw new notimplementedexception(); }
    }

    public waithandle asyncwaithandle
    {
        get { throw new notimplementedexception(); }
    }

    public bool completedsynchronously
    {
        get { throw new notimplementedexception(); }
    }

    public bool iscompleted
    {
        get { throw new notimplementedexception(); }
    }
}

这样肯定是不能用的,起码也得有个存回调函数的属性吧,下面我们稍微改造下:

然后我们可以自定义apm异步模型了:(成对的begin、end)

public iasyncresult mybeginxx(asynccallback callback)
{
    var asyncresult = new mywebrequest(callback, null);
    var request = webrequest.create("https://github.com/");
    new thread(() =>  //重新启用一个线程
    {
        using (streamreader sr = new streamreader(request.getresponse().getresponsestream()))
        {
            var str = sr.readtoend();
            asyncresult.setcomplete(str);//设置异步结果
        }

    }).start();
    return asyncresult;//返回一个iasyncresult
}

public string myendxx(iasyncresult asyncresult)
{
    mywebrequest result = asyncresult as mywebrequest;
    return result.result;
}

调用如下:

private void button4_click(object sender, eventargs e)
 {
     debug.writeline("【debug】主线程id:" + thread.currentthread.managedthreadid);
     mybeginxx(new asynccallback(t =>
     {
         var result = myendxx(t);
         debug.writeline("【debug】" + result.trim().substring(0, 100) + "...");
         debug.writeline("【debug】异步线程id:" + thread.currentthread.managedthreadid);
     }));
     debug.writeline("【debug】主线程id:" + thread.currentthread.managedthreadid);
 }

效果图:

我们看到自己实现的效果基本上和系统提供的差不多。

  • 启用异步方法并没有是ui界面卡死
  • 异步方法启动了另外一个id为11的线程

【总结】

个人觉得apm异步模式就是启用另外一个线程执行耗时任务,然后通过回调函数执行后续操作。

apm还可以通过其他方式获取值,如:

while (!asyncresult.iscompleted)//循环,直到异步执行完成 (轮询方式)
{
    thread.sleep(100);
}
var stream2 = request.endgetresponse(asyncresult).getresponsestream();

asyncresult.asyncwaithandle.waitone();//阻止线程,直到异步完成 (阻塞等待)
var stream2 = request.endgetresponse(asyncresult).getresponsestream();

补充:如果是普通方法,我们也可以通过委托异步:(begininvoke、endinvoke)

public void myaction()
 {
     var func = new func<string, string>(t =>
     {
         thread.sleep(2000);
         return "name:" + t + datetime.now.tostring();
     });
 
     var asyncresult = func.begininvoke("张三", t =>
     {
         string str = func.endinvoke(t);
         debug.writeline(str);
     }, null); 
 }

eap

eap 基于事件的异步模式,event-based asynchronous pattern

此模式在c#2的时候随之而来。

先来看个eap的例子:

private void button3_click(object sender, eventargs e)
 {            
     debug.writeline("【debug】主线程id:" + thread.currentthread.managedthreadid);

     backgroundworker worker = new backgroundworker();
     worker.dowork += new doworkeventhandler((s1, s2) =>
     {
         thread.sleep(2000);
         debug.writeline("【debug】异步线程id:" + thread.currentthread.managedthreadid);
     });//注册事件来实现异步
     worker.runworkerasync(this);
     debug.writeline("【debug】主线程id:" + thread.currentthread.managedthreadid);
 }

【效果图】(同样不会阻塞ui界面)

【特征】

  • 通过事件的方式注册回调函数
  • 通过 xxxasync方法来执行异步调用

例子很简单,但是和apm模式相比,是不是没有那么清晰透明。为什么可以这样实现?事件的注册是在干嘛?为什么执行runworkerasync会触发注册的函数?

感觉自己又想多了…

我们试着反编译看看源码:

只想说,这么玩,有意思吗?

tap

tap 基于任务的异步模式,task-based asynchronous pattern

到目前为止,我们觉得上面的apm、eap异步模式好用吗?好像没有发现什么问题。再仔细想想…如果我们有多个异步方法需要按先后顺序执行,并且需要(在主进程)得到所有返回值。

首先定义三个委托:

public func<string, string> func1()
{
    return new func<string, string>(t =>
    {
        thread.sleep(2000);
        return "name:" + t;
    });
}
public func<string, string> func2()
{
    return new func<string, string>(t =>
    {
        thread.sleep(2000);
        return "age:" + t;
    });
}
public func<string, string> func3()
{
    return new func<string, string>(t =>
    {
        thread.sleep(2000);
        return "sex:" + t;
    });
}

然后按照一定顺序执行:

public void myaction()
{
    string str1 = string.empty, str2 = string.empty, str3 = string.empty;
    iasyncresult asyncresult1 = null, asyncresult2 = null, asyncresult3 = null;
    asyncresult1 = func1().begininvoke("张三", t =>
    {
        str1 = func1().endinvoke(t);
        debug.writeline("【debug】异步线程id:" + thread.currentthread.managedthreadid);
        asyncresult2 = func2().begininvoke("26", a =>
        {
            str2 = func2().endinvoke(a);
            debug.writeline("【debug】异步线程id:" + thread.currentthread.managedthreadid);
            asyncresult3 = func3().begininvoke("男", s =>
            {
                str3 = func3().endinvoke(s);
                debug.writeline("【debug】异步线程id:" + thread.currentthread.managedthreadid);
            }, null);
        }, null);
    }, null);

    asyncresult1.asyncwaithandle.waitone();
    asyncresult2.asyncwaithandle.waitone();
    asyncresult3.asyncwaithandle.waitone();
    debug.writeline(str1 + str2 + str3);
}

除了难看、难读一点好像也没什么 。不过真的是这样吗?

asyncresult2是null?

由此可见在完成第一个异步操作之前没有对asyncresult2进行赋值,asyncresult2执行异步等待的时候报异常。那么如此我们就无法控制三个异步函数,按照一定顺序执行完成后再拿到返回值。(理论上还是有其他办法的,只是会然代码更加复杂)

是的,现在该我们的tap登场了。

只需要调用task类的静态方法run,即可轻轻松松使用异步。

获取返回值:

var task1 = task<string>.run(() =>
{
    thread.sleep(1500);
    console.writeline("【debug】task1 线程id:" + thread.currentthread.managedthreadid);
    return "张三";
});
//其他逻辑            
task1.wait();
var value = task1.result;//获取返回值
console.writeline("【debug】主 线程id:" + thread.currentthread.managedthreadid);

现在我们处理上面多个异步按序执行:

console.writeline("【debug】主 线程id:" + thread.currentthread.managedthreadid);
string str1 = string.empty, str2 = string.empty, str3 = string.empty;
var task1 = task.run(() =>
{
    thread.sleep(500);
    str1 = "姓名:张三,";
    console.writeline("【debug】task1 线程id:" + thread.currentthread.managedthreadid);
}).continuewith(t =>
{
    thread.sleep(500);
    str2 = "年龄:25,";
    console.writeline("【debug】task2 线程id:" + thread.currentthread.managedthreadid);
}).continuewith(t =>
{
    thread.sleep(500);
    str3 = "爱好:妹子";
    console.writeline("【debug】task3 线程id:" + thread.currentthread.managedthreadid);
});

thread.sleep(2500);//其他逻辑代码

task1.wait();

debug.writeline(str1 + str2 + str3);
console.writeline("【debug】主 线程id:" + thread.currentthread.managedthreadid);

[效果图]

我们看到,结果都得到了,且是异步按序执行的。且代码的逻辑思路非常清晰。如果你感受还不是很大,那么你现象如果是100个异步方法需要异步按序执行呢?用apm的异步回调,那至少也得异步回调嵌套100次。那代码的复杂度可想而知。

延伸思考

  • waitone完成等待的原理
  • 异步为什么会提升性能
  • 线程的使用数量和cpu的使用率有必然的联系吗

问题1:waitone完成等待的原理

在此之前,我们先来简单的了解下多线程信号控制autoresetevent类。

var _asyncwaithandle = new autoresetevent(false);
_asyncwaithandle.waitone();

此代码会在waitone的地方会一直等待下去。除非有另外一个线程执行autoresetevent的set方法。

var _asyncwaithandle = new autoresetevent(false);
_asyncwaithandle.set();
_asyncwaithandle.waitone();

如此,到了waitone就可以直接执行下去。没有有任何等待。

现在我们对apm 异步编程模型中的waitone等待是不是知道了点什么呢。我们回头来实现之前自定义异步方法的异步等待。

public class mywebrequest : iasyncresult
{
    //异步回调函数(委托)
    private asynccallback _asynccallback;
    private autoresetevent _asyncwaithandle;
    public mywebrequest(asynccallback asynccallback, object state)
    {
        _asynccallback = asynccallback;
        _asyncwaithandle = new autoresetevent(false);
    }
    //设置结果
    public void setcomplete(string result)
    {
        result = result;
        iscompleted = true;
        _asyncwaithandle.set();
        if (_asynccallback != null)
        {
            _asynccallback(this);
        }
    }
    //异步请求返回值
    public string result { get; set; }
    //获取用户定义的对象,它限定或包含关于异步操作的信息。
    public object asyncstate
    {
        get { throw new notimplementedexception(); }
    }
    // 获取用于等待异步操作完成的 system.threading.waithandle。
    public waithandle asyncwaithandle
    {
        //get { throw new notimplementedexception(); }

        get { return _asyncwaithandle; }
    }
    //获取一个值,该值指示异步操作是否同步完成。
    public bool completedsynchronously
    {
        get { throw new notimplementedexception(); }
    }
    //获取一个值,该值指示异步操作是否已完成。
    public bool iscompleted
    {
        get;
        private set;
    }
}

红色代码就是新增的异步等待。

【执行步骤】

问题2:异步为什么会提升性能

比如同步代码:

thread.sleep(10000);//假设这是个访问数据库的方法
thread.sleep(10000);//假设这是个访问翻墙网站的方法

这个代码需要20秒。

如果是异步:

var task = task.run(() =>
{
    thread.sleep(10000);//假设这是个访问数据库的方法
});
thread.sleep(10000);//假设这是个访问翻墙网站的方法
task.wait();

如此就只要10秒了。这样就节约了10秒。

如果是:

var task = task.run(() =>
{
    thread.sleep(10000);//假设这是个访问数据库的方法
}); 
task.wait();

异步执行中间没有耗时的代码那么这样的异步将是没有意思的。

或者:

var task = task.run(() =>
{
    thread.sleep(10000);//假设这是个访问数据库的方法
}); 
task.wait();
thread.sleep(10000);//假设这是个访问翻墙网站的方法

把耗时任务放在异步等待后,那这样的代码也是不会有性能提升的。

还有一种情况:

如果是单核cpu进行高密集运算操作,那么异步也是没有意义的。(因为运算是非常耗cpu,而网络请求等待不耗cpu)

问题3:线程的使用数量和cpu的使用率有必然的联系吗

答案是否。

还是拿单核做假设。

情况1:

long num = 0;
while (true)
{
    num += new random().next(-100,100);
    //thread.sleep(100);
}

单核下,我们只启动一个线程,就可以让你cpu爆满。

启动八次,八进程cpu基本爆满。

情况2:

一千多个线程,而cpu的使用率竟然是0。由此,我们得到了之前的结论,线程的使用数量和cpu的使用率没有必然的联系。

虽然如此,但是也不能毫无节制的开启线程。因为:

  • 开启一个新的线程的过程是比较耗资源的。(可是使用线程池,来降低开启新线程所消耗的资源)
  • 多线程的切换也是需要时间的。
  • 每个线程占用了一定的内存保存线程上下文信息。

以上就是c#异步的世界(上)的详细内容,更多关于c#异步的世界的资料请关注www.887551.com其它相关文章!