当前位置: 代码迷 >> C# >> WPF线程怎么搞?多线程怎么写入ObservableCollection<T>
  详细解决方案

WPF线程怎么搞?多线程怎么写入ObservableCollection<T>

热度:506   发布时间:2016-04-28 08:38:37.0
WPF线程如何搞?多线程如何写入ObservableCollection<T>

namespace WpfApplication1.VM
{
    class MainWindow
    {
        Random rd = new Random();

        private System.Collections.ObjectModel.ObservableCollection<Person> _persons;

        public System.Collections.ObjectModel.ObservableCollection<Person> Persons
        {
            get { return _persons; }
        }

        private DelegateCommand _refresh;

        public DelegateCommand Refresh
        {
            get { return _refresh; }
        }

        public MainWindow()
        {
            _persons = new System.Collections.ObjectModel.ObservableCollection<Person>();
            _refresh = new DelegateCommand();
            _refresh.Func = o => true;
            _refresh.ExecuteCommand = o =>
            {
                System.Threading.Tasks.Task.Factory.StartNew(() =>
                {
                    System.Threading.Thread.Sleep(5000);
                    var p = new Person(string.Empty) { Name = "testUser" };
                    p.TrackId = rd.Next(-5, 5) > 0 ? "hello" : string.Empty;
                    _persons.Add(p);
                });

            };
        }
    }


System.NotSupportedException”类型的第一次机会异常在 PresentationFramework.dll 中发生

多线程如何写入ObservableCollection<T>?
------解决思路----------------------
Dispatcher.Invoke(new Action(()=>{  ?_persons.Add(p);  }));

------解决思路----------------------
private readonly Dispatcher _dispatcher = Dispatcher.CurrentDispatcher;
 _dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
            {
               //TODO:
            }));
------解决思路----------------------
没有跨线程,应该不是这个问题吧。Add也没问题。估计问题出在Command上,没代码看不出来