(C# code below)
I am just staring to learn about Async and Await. I've checked a few articles and tutorials, and I thought I got the concept behind it but I seem to hit the wall when implementing some practical examples.
This is the New() of my UI class:
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
PopulateUI()
End Sub
...so the key here is PopulateUI(). I want to use this function without blocking the UI.
The only option I came out with which the compiler could accept is:
Private Async Sub PopulateUI()
Await Task.Run(Sub()
' Do some stuff that populates the UI comboboxes
End Sub)
End Sub
...this option does not work, and I think it is because Task.Run runs in a different thread so weird things occur when updating the comboboxes (sorry for being so vague about the description, I really don't know better).
So I found a similar SO question which didn't have any satisfactory answer, which makes me think is not that simple. Hopefully I'm wrong.
C# version:
public MyUI()
{
// This call is required by the designer.
InitializeComponent();
// Add any initialization after the InitializeComponent() call.
PopulateUI();
}
Private async void PopulateUI()
{
await Task.Run(() =>
{
// Do some stuff that populates the UI comboboxes
})
}
PopulateUI? Populating UI with content should be done on the UI thread; you should only run stuff that fetches/initializes the data off that thread.Loadedif this is WPF).Task.Run()of the fetch operation, wait for it in the main thread and then populate the combobox in the main thread as you suggest?