2015-06-23 45 views
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()); 
     } 
    } 

为什么会发生这种情况?

回答

2

您正在致电ResultWait某处。

这是一个classic ASP.NET deadlock.不要阻塞。 Task.Run是一种解决方法,因为它将删除其正文中的同步上下文。