.netparallel-processingtelerik-scheduler

How to update UI (telerik scheduler) correctly using Parallel.ForEach


I am experimenting Parallel Programming for the first time and i am using it to improve the speed filtering on the Telerik Scheduler control.

this is the code i am using to filter appointments by room, ex:

Task.Factory.StartNew(() =>
{
    SchedulerView view = this.radScheduler1.ActiveView;
    //ConcurrentBag<Classes.Appointment> _bag;

    if (InvokeRequired) Invoke((Action)(delegate
    {
        this.radScheduler1.Appointments.BeginUpdate();

        _itemsview = appointments.AsEnumerable().Where(app => app.Start >= view.StartDate && app.End < view.EndDate.AddDays(1)).ToList();

        //_bag = new ConcurrentBag<Classes.Appointment>(_itemsview);    
        Parallel.ForEach(_itemsview, item =>
        {
            if (_unidades.Contains(item.Room.ToString()))
            {
                 item.Visivel = true;
            }
            else
            {
                 item.Visivel = false;
            }
        });

        this.radScheduler1.Appointments.EndUpdate();
        this.radScheduler1.Select();
    }));
 });

What happens next, is that i can see sometimes other appointments that felled of the filter. I know that the number of appointments filtered is always right, but not always i see the right appointments on the screen. What is happening ?


Solution

  • In general, you'll need to update your UI elements on the main thread. Even if you are using WPF and update a bound property on a background thread, the WPF system still has to marshall that back to the UI.

    This means, in your case, since your "work" is completely updating the UI and bound properties, you'd be better off just doing it directly on the UI thread. The Parallel.ForEach, in this case, is likely to make the entire operation less stable and likely slower, as well.