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());
}
}
为什么会发生这种情况?