如何实施从等待中恢复? [英] How is resumption from await implemented?

查看:102
本文介绍了如何实施从等待中恢复?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读Eric Lippert在C#5中有关异步的博客文章(

I've been reading Eric Lippert's blog posts on Asynchrony in C# 5 (part 4 being particular relevant) and have watched Anders PDC10 talk on the subject and I'm unclear on how continuations from asynchronous methods are resumed in a single threaded context.

这两个消息源都讨论了在单线程UI循环中使用异步方法来提高响应性,并且在Anders的示例中,他提到当异步任务完成时,它的继续是通过向消息泵中添加消息来安排的.

Both sources discuss using asynchronous methods in a single threaded UI loop to improve responsiveness and in Anders' example he mentions that when an asynchronous task completes it's continuation is scheduled by the addition of a message to the message pump.

异步方法是否真的知道它需要执行似乎特定于上下文的操作,或者这是一种简化?

Does the asynchronous method really know that it needs to perform what seems like a context specific action, or was this a simplification?

更一般地说,如何在单个线程上下文中从异步方法中恢复?是否需要在单个线程中进行调度?

More generally, how can resumption from asynchronous methods handled in a single threaded context? Is there a requirement for scheduling within a single thread?

推荐答案

任务继续知道需要在何处安排继续-例如任何线程池线程"或"UI线程".

The task continuation knows where the continuation needs to be scheduled - e.g. "any thread pool thread" or "the UI thread".

但是,此行为由等待者"确定-实际上,它不是C#编译器负责的一部分.编译器仅调用 BeginAwait 并传递继续.等待者将返回一个布尔值,该值指示任务是否已经同步完成,或者调用方是否应返回并让继续执行异步进行.

This behaviour is determined by the "awaiter", however - it's not actually part of what the C# compiler is responsible for. The compiler just calls BeginAwait and passes in the continuation; the awaiter returns a Boolean value indicating whether the task has already completed synchronously, or whether the caller should return and let the continuation occur asynchronously.

因此,目前,该决定是在 TaskEx 返回的等待者中做出的-但如果最终将它们全部捆绑到 Task 中,我不会感到惊讶.这样可以像同步上下文一样流动,它知道应该如何处理进一步的动作.

So for the moment, that decision is made in the awaiter returned by TaskEx - but I wouldn't be surprised to see it all get bundled into Task eventually. That can flow things like the synchronization context, which knows how further actions should be handled.

我不确定您正在考虑使用哪种真正单线程上下文...或者您是否正在考虑需要大量工作在单个环境中完成的情况线程,但是异步位可能涉及其他线程(例如,当接收到HTTP数据包,在IO完成端口线程上进行处理,并且响应 handled 返回UI线程时)?

I'm not quite sure what sort of genuinely single-threaded context you're considering... or are you thinking of a situation where the bulk of the work needs to happen in a single thread, but other threads can be involved for the asynchronous bit (e.g. when an HTTP packet is received, processed on an IO completion port thread, and the response handled back on the UI thread)?

这篇关于如何实施从等待中恢复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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