question

Allanjb avatar image
0 Votes"
Allanjb asked RoyLi-MSFT commented

Running Async methods from the UWP MainPage Constructor.

When building UWP apps, a chain of Async methods is inevitable and invariably ends up at the UWP MainPage constructor or another synchronous method.

The compiler will warn you that an await operator can only be used in an async method, leaving out the await will also warn you that because the call s not awaited, execution of the current method continues before the call is completed. So the developer is left in a quandary.
In my case, I can get round this by placing async methods in the Loaded event of the main page and making it async, but what if this was not possible, what then?

For example I have a method that initializes a mainpage treeview control with StorageFolder items. I have added the Async keyword to my MainPage Loaded event handler which returns void.

So what I am asking is: how do you end an async chain of methods in a UWP or WPF app?
There are lots of examples that illustrate the async/await process when running in a console app, but I cannot find a good example the illustrates this for a uwp app, that is using async/await on the UI thread, (handing controls for example like treeview or gridview).

windows-uwpdotnet-wpf-xaml
· 5
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

how do you end an async chain of methods in a UWP or WPF app?

It confused me about what do you really want to ask. Could you please tell me what do you really want to implement? You could call the async method without using await, it just will run the code synchronously.

0 Votes 0 ·

When developing Console apps, Microsoft have provided: static async Task Main(string[] args)
for handling await's in the class constructor. This I like and can understand.
There seems to be no thought given to providing the same logic to handle await calls in the constructor of MainPage in a UWP app? unless I am missing something....


0 Votes 0 ·

Why do you want to call await calls in the constructor? This behavior is by design. You have many other options like loaded event and the OnLaunched event of the app.cs.

0 Votes 0 ·
Show more comments

0 Answers