I can't await my task when i load window. I have three viewmodel
, with three initialize
, and this three initialize have 1 async method to return data from database, and 1 synchronous method. If i try load this data i have exception (ViewModel return null
) or my load animation (binded to property) set hidden.
TLDR: Window.Load
don't wait when task is complete (like synchronus method been in this task), and fire next.
I search for answer in google, and stack but nothing work for me and CogAnim set False before.
I try doing this in Task.Factory
like this
public MainWindow()
{
CogAnim = true;
InitializeComponent();
DataContext = this;
Loaded += MainWindow_Loaded;
}
public bool CogAnim { get; set; }
private async void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
var t = await Task.Factory.StartNew(async () =>
{
await Task.Run(() => ViewModelOne = new ViewModelOne());
await Task.Run(() => ViewModelTwo = new ViewModelTwo());
await Task.Run(() => ViewModelThree = new ViewModelThree());
}).ContinueWith((t1) => ViewModelOne.Initialize()).ContinueWith((t2) => ViewModelTwo.Initialize()).ContinueWith((t3) => ViewModelThree.Initialize());
t.Wait();
CogAnim = false;
OnPropertyChanged("CogAnim");
}
And try without this await Task.Run(() => {modelname})
.
How properly create ViewModels, and use Initialize in it without freeze window? Only work when i do it like this but this freeze gui and load animation dont work
private async void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
ViewModelOne = new ViewModelOne();
ViewModelTwo = new ViewModelTwo();
ViewModelThree = new ViewModelThree();
await ViewModelOne.Initialize();
await ViewModelTwo.Initialize();
await ViewModelThree.Initialize();
CogAnim = false;
OnPropertyChanged("CogAnim");
}
This Initialize
method look like this (maybe there is problem):
public async Task Initialize()
{
await Task.Delay(2000);
var t = Repo.GetOne();
foreach(var a in t)
{
CollectionOne.Add(a);
}
await Select();
}
public async Task Select()
{
var t = await Repo.GetOneAsync();
foreach(var a in t)
{
CollectionOne.Add(a);
}
}