我认为 await 继续与调用者在同一线程上,但似乎没有 [英] I thought await continued on the same thread as the caller, but it seems not to

查看:27
本文介绍了我认为 await 继续与调用者在同一线程上,但似乎没有的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为关于 async/await 的要点之一是,当任务完成时,continuation 在调用 await 时在同一上下文中运行,在我的情况下,这将是 UI 线程.

I thought one of the points about async/await is that when the task completes, the continuation is run on the same context when the await was called, which would, in my case, be the UI thread.

例如:

Debug.WriteLine("2: Thread ID: " + Thread.CurrentThread.ManagedThreadId);
await fs.ReadAsync(data, 0, (int)fs.Length);
Debug.WriteLine("3: Thread ID: " + Thread.CurrentThread.ManagedThreadId);

我不希望这样:

2: Thread ID: 10
3: Thread ID: 11

什么给?为什么continuation 的线程ID 与UI 线程不同?

What gives? Why is the thread ID for the continuation different than the UI thread?

根据这篇文章[^] 我需要显式调用 ConfigureAwait 来更改延续上下文的行为!

According to this article[^] I would need to explicitly call ConfigureAwait to change the behavior of the continuation context!

推荐答案

当你 await 时,默认情况下 await 操作符将捕获当前的上下文"并使用它恢复 async 方法.

When you await, by default the await operator will capture the current "context" and use that to resume the async method.

这个上下文"是SynchronizationContext.Current,除非它是null,在这种情况下它是TaskScheduler.Current.(如果没有当前正在运行的任务,则TaskScheduler.CurrentTaskScheduler.Default 相同,线程池任务调度器).

This "context" is SynchronizationContext.Current unless it is null, in which case it is TaskScheduler.Current. (If there is no currently-running task, then TaskScheduler.Current is the same as TaskScheduler.Default, the thread pool task scheduler).

需要注意的是,SynchronizationContextTaskScheduler 不一定意味着特定的线程.UI SynchronizationContext 将工作安排到 UI 线程;但 ASP.NET SynchronizationContext 不会将工作安排到特定线程.

It's important to note that a SynchronizationContext or TaskScheduler does not necessarily imply a particular thread. A UI SynchronizationContext will schedule work to the UI thread; but the ASP.NET SynchronizationContext will not schedule work to a particular thread.

我怀疑您的问题的原因是您过早地调用了 async 代码.当应用程序启动时,它只有一个普通的旧常规线程.该线程仅在执行诸如 Application.Run 之类的操作时才成为 UI 线程.

I suspect that the cause of your problem is that you are invoking the async code too early. When an application starts, it just has a plain old regular thread. That thread only becomes the UI thread when it does something like Application.Run.

这篇关于我认为 await 继续与调用者在同一线程上,但似乎没有的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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