如何在异步之后在主线程上运行代码



我有只在主线程上运行的代码,但在该代码运行之前,我需要初始化一个对象。我是否可以强制异步代码运行sync?等待之后的函数是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
}
}

您不能在构造函数中使用await,但您可以将整个过程放入订阅Window:的Loaded事件的异步事件处理程序中

public MainWindow()
{
this.Loaded += async (s, e) => 
{
await InitMbi(); 
// mbi must be done at this point
SomeCodeThatUsesMbi();
};
InitializeComponent();
}

不要忘记将InitMbi()的返回值更改为Task:

public async Task InitMbi()
// is there any way i can run these two methods as not await and
// run them synchronous?

是的,只需在方法调用之前删除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?
}

但请注意,这将阻塞您的主线程!