Reputation: 708
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.
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
}
}
Upvotes: 1
Views: 1352
Reputation: 6592
// 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:
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!
Upvotes: 1
Reputation: 898
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
:
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
:
public async Task InitMbi()
Upvotes: 4