[英]How to run code on the main thread after async
I have code that will only run on the main thread, but before that code can run, I need to initialize an object. 我的代码只能在主线程上运行,但是在该代码可以运行之前,我需要初始化一个对象。 Is there anyway I can force async code to run sync?
无论如何,我可以强制异步代码运行同步吗? The functions after the awaits are API calls, and therefore I cannot modify those directly.
等待之后的函数是API调用,因此我无法直接修改它们。
public partial class MainWindow : Window
{
private MustBeInit mbi;
public MainWindow() {
InitializeComponent();
// async code that initializes mbi
InitMbi();
// mbi must be done at this point
SomeCodeThatUsesMbi();
}
public async void InitMbi() {
mbi = new MustBeInit();
await mbi.DoSomethingAsync();
await mbi.DoSomethingElseAsync();
// is there any way i can run these two methods as not await and
// run them synchronous?
}
public void SomeCodeThatUsesMbi() {
DoSomethingWithMbi(mbi); // mbi cannot be null here
}
}
You can't use the await in constructors, but you can put the whole thing into an async event handler subscribed to the Loaded
event of the Window
: 您不能在构造函数中使用await,但可以将整个内容放入预订
Window
的Loaded
事件的异步事件处理程序中:
public MainWindow()
{
this.Loaded += async (s, e) =>
{
await InitMbi();
// mbi must be done at this point
SomeCodeThatUsesMbi();
};
InitializeComponent();
}
And don't forget to change the return value of your InitMbi()
to Task
: 并且不要忘记将
InitMbi()
的返回值更改为Task
:
public async Task InitMbi()
// is there any way i can run these two methods as not await and // run them synchronous?
Yes, just remove the await
before the method call like: 是的,只需在方法调用之前删除
await
:
public async void InitMbi() {
mbi = new MustBeInit();
mbi.DoSomethingAsync();
mbi.DoSomethingElseAsync();
// is there any way i can run these two methods as not await and
// run them synchronous?
}
But be aware of the fact that this will block your main thread! 但是请注意,这将阻塞您的主线程!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.