0
ToListAsync塊UI我有下一視圖模型:實體框架在第一執行
public class ExampleViewModel : INotifyPropertyChanged
{
public ICommand TestCommand { get; private set; }
private IEnumerable<Databases.Main.Models.Robot> _testCollection;
public IEnumerable<Databases.Main.Models.Robot> TestCollection
{
get { return _testCollection; }
private set
{
_testCollection = value;
var handler = Volatile.Read(ref PropertyChanged);
if (handler != null)
{
handler(this, new PropertyChangedEventArgs("TestCollection"));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
public ExampleViewModel()
{
TestCommand = DelegateCommand.FromAsyncHandler(Test);
}
private async Task Test()
{
using (var context = new AtonMainDbContext())
{
TestCollection = await context.Set<Databases.Main.Models.Robot>().ToListAsync();
}
}
}
和下XAML:
<Button Content="Refresh"
Command="{Binding TestCommand}"/>
<ListBox ItemsSource="{Binding TestCollection}"
DisplayMemberPath="Name"/>
當我執行TestCommand,UI凍結在第一執行幾秒鐘。我不喜歡它。 但是,如果我不使用ToListAsync,只是用Task包裝ToList方法,那麼一切工作正常,用戶界面不會凍結。
private async Task Test()
{
using (var context = new AtonMainDbContext())
{
TestCollection = await Task.Run(() => context.Set<Databases.Main.Models.Robot>().ToList());
}
}
爲什麼會發生這種情況?