如何C#5异步返回主线程

如何C#5异步返回主线程

本文介绍了如何C#5异步返回主线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在看一个关于异步CTP VID和已经看到,如果从呼叫等待例如主线程,那么将继续执行从主线程工作完成时。

I was watching a vid about Async CTP and saw that if you call await from e.g. main thread , then the execution will continue from main thread when the work is completed.

例如

//called from main thread
var result = await SomeAsyncWork();
//this will execute in main thread also
console.writeline(result)

我有天真的IM pression会有一个正常的回调正在进行这将是一个工作线程执行。

I had the naive impression that there would be a normal call back going on which would be executed on a worker thread.

目前必须到底是怎么回事,因为你可以用正常的异步方法在T的任务与Task.FromAsync一定程度

At some level that must be what is going on since you can wrap normal async methods in a Task of T with Task.FromAsync

但正常的异步方法将在工作线程中运行,因此如何在的WorkerThread回调整理回主线程?

but normal async methods will run in worker threads, so how is the callback in the workerthread marshalled back to the main thread?

推荐答案

回调连接到任务,使用当前的任务调度程序(这是在等待的时间当前,在完成时没有电流)。对于UI线程,当前的任务调度将安排回调将在UI线程中执行......一个线程池线程,调度程序将允许它上的任何的线程池线程中执行,等等。

The callback is attached to the task, using the current task scheduler (that's "current" at the time of awaiting, not current at the time of completion). For a UI thread, the current task scheduler will schedule the callback to be executed within the UI thread... for a thread pool thread, the scheduler will allow it to be executed on any thread pool thread, etc.

假设你正在等待任务&LT; T&GT; ,它有效地调用<$c$c>Task<T>.ContinueWith(continuationAction,调度程序) 。

Assuming you're awaiting a Task<T>, it's effectively calling Task<T>.ContinueWith(continuationAction, scheduler).

您可以等待可用正确的方法什么,而是如何 BeginAwait 时间表的延续是实现特定的。因为它可能是最常见的一种,我只提到了基于任务之一。本身并没有指定这个在所有的编译器 - 它假定库将做正确的事情。所有的编译器是翻译方法的其余部分变成了延续,并传递到 BeginAwait

You can await anything with the right methods available, but how BeginAwait schedules the continuation is implementation-specific. I've only mentioned the task-based one because it's probably the most common one. The compiler itself doesn't specify this at all - it assumes that the libraries will do the right thing. All the compiler does is translate "the rest of the method" into a continuation, and pass that into BeginAwait.

这篇关于如何C#5异步返回主线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 08:17