-1

In my program i have one page with viewmodel. Viewmodel executes Update function every 10 sec in another thread with a Timer:

// in viewmodel ctor
var timer = new Timer(Update, 0, 10000);

public ObservableCollection<Tick> Data { get; set; }

public void Update(object state)
{
    var query = xbtceService.GetAllTicksAsync(); // get data from service
    query.Wait();
    var data = query.Result;
    if (data.Any())
    {
        dataAccess.SaveItems(data); //save data in database
    }

    Data.Clear(); // ERROR, another thread
    var list = dataAccess.LoadList();
    foreach (var item in list)
    {
        Data.Add(item);
    }
}

Also viewmodel have ObservableCollection that Binded to a ListView. How to fill ObservableCollection from another thread with new data every 10 sec?

Nickolay Kabash
  • 75
  • 2
  • 11

2 Answers2

0

You should use DispatcherTimer,and if have the async want use ui,you can

           await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
            () =>
            {
                //code
            });
lindexi
  • 4,182
  • 3
  • 19
  • 65
0

System.Threading.Timer Class provides a mechanism for executing a method on a thread pool thread at specified intervals. And once you bind Data to a ListView, Data is associated with the UI thread. In UWP, we can't access UI thread form a worker thread directly. So as @lindexi said, we need to use CoreDispatcher.RunAsync method to schedule work on the UI thread. For example, you can change your Update method like following:

public async void Update(object state)
{
    var query = xbtceService.GetAllTicksAsync(); // get data from service
    query.Wait();
    var data = query.Result;
    if (data.Any())
    {
        dataAccess.SaveItems(data); //save data in database
    }

    await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
    {
        Data.Clear();
        var list = dataAccess.LoadList();
        foreach (var item in list)
        {
            Data.Add(item);
        }
    });
}
Jay Zuo
  • 15,653
  • 2
  • 25
  • 49