[英]WPF await switches from the UI thread
I have a function called from the UI thread, I'm double checking if that's so by我有一个从 UI 线程调用的函数,我正在仔细检查是否是这样
System.Windows.Threading.Dispatcher.FromThread(System.Threading.Thread.CurrentThread)
everything is called from a void
method, which can't be async void
because it has an out
parameter (method from 3rd party API).一切都是从
void
方法调用的,它不能是async void
因为它有一个out
参数(来自 3rd 方 API 的方法)。
So in this void
method I make a call to an async
method, the main method doesn't have to wait, so I just run it and forget (planning to handle exceptions in the ContinueWith
method, but I'm not there yet).所以在这个
void
方法中,我调用了一个async
方法,主方法不必等待,所以我只是运行它并忘记(计划在ContinueWith
方法中处理异常,但我还没有)。
Problem is, that when in the method chain an await
is performed on the ExecuteTaskAsync
method of the RestSharp client, after that line, the thread is witched to MTA, the SynchronizationContext.Current
is different too.问题是,当在方法链中对 RestSharp 客户端的
ExecuteTaskAsync
方法执行await
,在该行之后,线程被切换到 MTA, SynchronizationContext.Current
也不同。
Why is this happening?为什么会这样? Shouldn't the
await
keyword return to the orginal SynchronizationContext? await
关键字不应该返回到原始 SynchronizationContext 吗? Why is the SynchronizationContext.Current
changing during that call?为什么
SynchronizationContext.Current
在该调用期间发生变化?
Sorry for no code snippets, it's a part of a bigger app and it's hard to snippet it out, but I'm doing it right now, so code snippets will be added.抱歉没有代码片段,它是更大应用程序的一部分,很难将其片段化,但我现在正在做,因此将添加代码片段。
Ok, resolved it, the mentioned void
method from the 3rd party API, was running with a thread that has a dispatcher, because好的,解决了它,提到的第 3 方 API 中的
void
方法正在使用具有调度程序的线程运行,因为
System.Windows.Threading.Dispatcher.FromThread(System.Threading.Thread.CurrentThread)
Returned a dispatcher, I don't know why, but that didn't matter, I had to run my async method in an Invoke
like返回了一个调度程序,我不知道为什么,但这没关系,我必须在
Invoke
运行我的异步方法,例如
Application.Current.Dispatcher.Invoke(() => myAsyncMethod());
and then the await
in my method didn't switched the SynchronizationContext
.然后我方法中的
await
没有切换SynchronizationContext
。 It looks like my assumption that when there is a dispatcher it's the proper context was wrong, don't know why :)看起来我的假设是,当有调度员时,正确的上下文是错误的,不知道为什么:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.