为什么嵌套异步计算? [英] Why nest async computations?

查看:50
本文介绍了为什么嵌套异步计算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下两种方式来构造用于计算 1 + 2 Async 计算:

 让c1 =异步{令a = 1令b = 2返回a + b}令c2 =异步{令a = 1让!b =异步{return 2}返回a + b} 

它们之间的实际区别是什么?在我看来,他们做同样的事情.例如,为什么要使用 let!result = streamReader.ReadToEndAsync()而不是 let result = streamReader.ReadToEnd()?两条线都阻塞"了吗?什么时候运行计算?

解决方案

您的带有 let的愚蠢示例!b =异步{return 2} 确实没有带来任何新变化.实际上,它完全等同于 let b = 2 .

这是另一回事,使用 ReadToEnd ReadToEndAsync .尽管它们都可以描述为阻止",但它们的阻止方式却大不相同.

ReadToEnd 是同步的.在线程上调用它时,该线程停止并等待其完成.线程被阻止.它什么也没做,但是也不能用来执行其他任何事情.

ReadToEndAsync 使用异步I/O (也在Windows上称为"重叠的I/O ".这基本上意味着线程在此时停止并调用OS,并说嘿,请为我阅读此文件,并在完成后唤醒我".较低级别的实现方式因操作系统而异,但通常在调用完成后会得到某种回调.

这在诸如HTTP服务器之类的高可用性高并发系统中很重要.但是,如果您只是在人工监督下在计算机上本地运行脚本,则只需使用更方便的方式即可.

有趣的是,同步版本 ReadToEnd 实际上也确实在后台使用了异步I/O,它只是包装在一个同步阻止包装中,以使在简单情况下使用起来更加方便./p>

Consider the following two ways of constructing an Async computation that calculates 1 + 2:

let c1 =
    async {
        let a = 1
        let b = 2
        return a + b }

let c2 =
    async {
        let a = 1
        let! b = async { return 2 }
        return a + b }

What is the practical difference between them? It seems to me that they do the same thing. Why, for example, would you ever need to use let! result = streamReader.ReadToEndAsync () rather than let result = streamReader.ReadToEnd ()? Isn't it the case that both lines are "blocking" when the computation is run?

解决方案

Your silly example with let! b = async { return 2 } is indeed not bringing anything new. It's indeed completely equivalent to let b = 2.

It is a different story, however, with ReadToEnd vs. ReadToEndAsync. While they can both be described as "blocking", they are blocking is quite different ways.

ReadToEnd is synchronous. When it's called on a thread, that thread stops and waits for it to complete. The thread is blocked. It's doing nothing, but it also can't be used to execute anything else.

ReadToEndAsync uses asynchronous I/O (also called "overlapped I/O" on Windows). This basically means that the thread stops at this point and calls the OS, saying "hey, please read this file for me and wake me up when you're done". The way it's implemented at a lower level differs depending on the OS, but generally you get some sort of callback when the call completes.

This is kind of important in high-availability high-concurrency systems, such as HTTP servers. But if you're just running a script locally on your computer under human supervision, then just use whatever is more convenient.

Interestingly, the sync version ReadToEnd does actually use async I/O under the hood as well, it's just wrapped in a sync-blocking wrapper to make it more convenient to use in simple cases.

这篇关于为什么嵌套异步计算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆