我的MyViewModel中有此方法:
private void Initialise()
{
IsBusy = true;
Task.Factory.StartNew(() =>
{
try
{
LoadTitles()
.ContinueWith(t => LoadNationalities())
.Wait();
}
catch (AggregateException ex)
{
Console.WriteLine(ex.Message);
}
}).ContinueWith(task => IsBusy = false);
}
我面临的问题是,我想将焦点设置到给定的TextBox上,并设置焦点,但是使用内部的Wait()方法,在我认为Wait()方法完成后,焦点移到了其他地方等待中
private void MyView_Loaded(object sender, EventArgs e)
{
Keyboard.Focus(txtHouse);
FocusManager.SetFocusedElement(this, txtHouse);
txtHouse.Focus();
txtHouse.Select(0, 0);
}
答案 0 :(得分:1)
该方法可能应该如下所示实现,而无需Task.Factory.StartNew,ContinueWith和Wait。
private async Task InitialiseAsync()
{
IsBusy = true;
try
{
await LoadTitlesAsync();
await LoadNationalitiesAsync();
}
finally
{
IsBusy = false;
}
}
并在被调用时等待:
await x.InitialiseAsync();