A community member has associated this post with a similar question:
Why is the GetReservations method not running asynchronously?

Only moderators can edit this content.

I'm having an issue with getting the method GetReservations() to run Asyncronously.

Tom Meier 140 Reputation points
2024-05-20T16:22:47.0766667+00:00

I'm having an issue with getting the method GetReservations() to run Asyncronously. And also the compiler doesnt like my private readonly _reservations variable. Any help would be greatly appreciated. Thanks !

public class ReservationListingViewModel:ViewModelBase
{
    private readonly  ObservableCollection<ReservationViewModel> _reservations;
    public IEnumerable<ReservationViewModel>  Reservations => _reservations;
    
    public  ReservationListingViewModel()
    {
        InitializeAsync();
    }
    private async Task InitializeAsync()
    {
        _reservations = await GetReservations();
    }
    public async Task <ObservableCollection<ReservationViewModel>> GetReservations()
    {
        _reservations = new ObservableCollection<ReservationViewModel>();
        for (int i = 0; i < 1000; i++)
        {
            _reservations.Add(new ReservationViewModel(new Reservation("1,2", "Ron" + i, DateTime.Now, DateTime.Now)));
        }
        
        return _reservations;
    }
   
}
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,420 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 58,441 Reputation points
    2024-05-20T17:01:07.1766667+00:00

    the readonly variable _reservations needs to be assigned in the constructor or definition.

    private readonly ObservableCollection<ReservationViewModel> _reservations = new();

    or

    public ReservationListingViewModel() 
    { 
       _reservations = new ObservableCollection<ReservationViewModel>();
       InitializeAsync(); 
    }
    

    also as GetReservations() has a couple issues

    • as _reservations is readonly it can not be set in his method
    • there is no async code, not sure why its a Task.
    • as ObservableCollection's do not implement thread concurrency, if you wanted an async load, you will need to add some synchronization logic to call from constructor, as the constructor can not wait for completion. and a user of the class should not access until the load is complete.
    0 comments No comments