0

I have a next view model:

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();
        }
    }
}

and next xaml:

            <Button Content="Refresh"
                    Command="{Binding TestCommand}"/>
            <ListBox ItemsSource="{Binding TestCollection}"
                     DisplayMemberPath="Name"/>

When i execute TestCommand, UI freeze at first execution for a few seconds. I don't like it. But if i don't use ToListAsync and just wrap ToList method with Task, that everything works fine and UI don't freeze.

    private async Task Test()
    {
        using (var context = new AtonMainDbContext())
        {
            TestCollection = await Task.Run(() => context.Set<Databases.Main.Models.Robot>().ToList());
        }
    }

Why this happened?

Spider man
  • 3,224
  • 4
  • 30
  • 42
l1pton17
  • 444
  • 4
  • 16

1 Answers1

2

You are calling Result or Wait somewhere.

That's a classic ASP.NET deadlock. Don't block. The Task.Run is a workaround because it removes the synchronization context in its body.

Community
  • 1
  • 1
usr
  • 168,620
  • 35
  • 240
  • 369