BertAR
BertAR

Reputation: 475

Property not set when using Task.Run

Vendors is bound to a combobox

//This works, Vendor is set
LoadVendors();
Vendor = Vendors.FirstOrDefault();

I would like LoadVendors() to Run in a separate thread, however Vendor is not set. Can somebody help?

//Doesn't work, Vendor is not set!
System.Threading.Tasks.Task.Run(() => LoadVendors()).ContinueWith((t) => Vendor = Vendors.FirstOrDefault());

Vendors

public ObservableCollection<Vendor> Vendors
    {
        get
        {
            return _vendors;
        }

        set
        {
            if (_vendors != value)
            {
                var oldVendors = new ObservableCollection<Vendor>(_vendors);
                _vendors = value;
                RaisePropertyChanged(nameof(Vendors), oldVendors, Vendors, true);
            }

        }
    }

LoadVendors

private void LoadVendors()
    {

            var vendors = DataHelper.GetVendors()
            DispatcherHelper.CheckBeginInvokeOnUI(() => Vendors.Clear());
            vendors.ForEach(dcpV =>
            {                    
                DispatcherHelper.CheckBeginInvokeOnUI(() => Vendors.Add(vendor));
            });
            RaisePropertyChanged(nameof(Vendors));

    }   

Upvotes: 1

Views: 396

Answers (1)

mm8
mm8

Reputation: 169200

Call the DataHelper.GetVendors method on the background thread and do everything else back on the UI thread:

Task.Factory.StartNew(()=> DataHelper.GetVendors())
    .ContinueWith(task => 
    {
        Vendors.Clear();
        foreach (var vendor in task.Result)
            Vendors.Add(vendor);
        RaisePropertyChanged(nameof(Vendors));
        Vendor = Vendors.FirstOrDefault();
    }, System.Threading.CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());

Upvotes: 2

Related Questions