Async and padding data for a WPF application

I have a WPF application that initializes the state of a user interface using methods in the constructor. However, it never returns from Wait();in the constructor.

Here is what I'm doing now with a pretty far-fetched pattern:

public class SomeViewModel
{
    public ICommand AddDataCommand { get { return RelayCommand(AddDataExecute); } }
    public ObservableCollection<int> UIData { /* Property with INotifyPropertyChanged */}   

    public SomeViewModel() 
    {
        //Load synch. here
        LoadData().Wait();      
    }

    public async Task LoadData()
    {
        UIData = await Task.Run(() => SomeService.SelectAllUIData());
    }

    public async void AddDataExecute()
    {
        //Add new data item to database on separate thread to keep UI responsive
        await Task.Run(() => SomeService.AddNewData(0));

        //Reload data from database and update UI, has to happen after AddNewData completes
        await LoadData();
    }
}

I believe that it hangs because I never return Task. However, I don’t know another way to assign UIData asynchronously, which works both in the constructor and in the commands that call it.

+4
source share
2 answers

, .

, async , MSDN async .

. , async . , ViewModel , , , async properties - , .

+8

, , . factory:

public class SomeViewModel
{
    private SomeViewModel() 
    { }

    public static async Task<SomeViewModel> Create()
    {
        SomeViewModel model = new SomeViewModel();
        await model.LoadData();
        return model;
    }

    public async Task LoadData()
    {
        UIData = await Task.Run(() => SomeService.SelectAllUIData());
    }

    //...
}

, , await, , , , , . " ", .

+6

Source: https://habr.com/ru/post/1524328/


All Articles