使用Task.Run时未设置属性

时间:2017-11-17 14:03:26

标签: c# wpf task task-parallel-library

供应商必须使用组合框

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

我希望LoadVendors()在单独的线程中运行,但是没有设置供应商。有人可以帮忙吗?

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

供应商

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));

    }   

1 个答案:

答案 0 :(得分:2)

在后台线程上调用DataHelper.GetVendors方法,然后在UI线程上执行其他操作:

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());