来自 UI 线程的 ReadToEndAsync [英] ReadToEndAsync from UI Thread

查看:14
本文介绍了来自 UI 线程的 ReadToEndAsync的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我从 Windows Phone 8 上的 UI 线程调用 await ReadToEndAsync,ReadToEndAsync 将在什么上下文中工作?任务是否会排队等待 UI 线程本身进行处理,还是由一个新线程来完成这项工作.

If I call await ReadToEndAsync from the UI thread on Windows Phone 8, on what context will ReadToEndAsync do its work? Will a task get queued for processing by the UI thread itself, or will a new thread do the work.

基于此:

http://blogs.msdn.com/b/ericlippert/archive/2010/11/04/asyncchrony-in-c-5-0-part-four-it-s-not-magic.aspx

它似乎会在 UI 线程上运行.

it seems like it will run on the UI thread.

推荐答案

这是 async 最纯粹形式的基本真理:没有线程.

This is an essential truth of async in its purest form: There is no thread.

对于真正的异步流,ReadToEndAsync 几乎没有任何工作要做.当您调用该方法时,它只是要求运行时读取到最后,并在操作完成时通知它(通过 Task).运行时转向操作系统,要求它读取,并在操作完成时通知它(例如,通过 IOCP).操作系统转向设备驱动程序,要求它读取,并在操作完成时通知它(例如,通过 IRP).设备驱动程序转向设备,要求它读取,并在操作完成时通知它(例如,通过 IRQ).

For a truly asynchronous stream, ReadToEndAsync has no almost work to do. When you call that method, it merely asks the runtime to read to the end, and notify it when the operation is complete (via a Task). The runtime turns to the OS, asks it to read, and notify it when the operation is complete (e.g., via an IOCP). The OS turns to the device driver, asks it to read, and notify it when the operation is complete (e.g., via an IRP). The device driver turns to the device, asks it to read, and notify it when the operation is complete (e.g., via an IRQ).

没有线程.

当然,这是理想的情况.在现实世界中,在某些时候,读取到结束"操作被分解为几个读取 n 字节"操作,这些操作需要重新拼接在一起.使用借用线程完成(微小的)工作量:内核模式代码的不可知线程和用户模式代码的线程池线程.

This is an ideal situation, of course. In the real world, at some point the "read to end" operation is broken up into several "read n byte" operations, and those need to be stitched back together. That (tiny) amount of work is done using borrowed threads: unknowable threads for kernel-mode code and thread pool threads for user-mode code.

此外,在某些情况下,异步 API 不存在.在这些情况下,异步工作是使用线程池线程伪造的.例如,如果您在 MemoryStream 上调用 ReadToEndAsync,则没有用于从内存读取的异步 API,因此这是将在线程池上运行的虚假异步操作.

Also, there are some situations where an asynchronous API does not exist. In those cases, asynchronous work is faked using a thread pool thread. For example, if you call ReadToEndAsync on a MemoryStream, there are no asynchronous APIs for reading from memory, so that is a fake asynchronous operation that will run on the thread pool.

但是总是必须有一个线程来执行异步操作的想法并不是事实.不要试图控制线程——这是不可能的.相反,只尝试了解真相:没有线程.

But the idea that there always must be a thread to execute an asynchronous operation is not the truth. Do not try to control the thread — that's impossible. Instead, only try to realize the truth: there is no thread.

扩展了这个答案进入博文.

这篇关于来自 UI 线程的 ReadToEndAsync的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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