日期:2014-05-18  浏览次数:21331 次

wpf 使用ObservableCollection 时 掉用多线程(下载)时
添加列队失效。。。。。。。

------解决方案--------------------
这些代码没什么问题,看插入数据的部分。
------解决方案--------------------
对于多线程需要特殊处理
C# code

   SynchronizationContext ctx = SynchronizationContext.Current;



   if (PropertyChanged != null)
            {
                if (ctx == null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(sender.GetType().ToString()));
                }
                else
                {
                    ctx.Send(p => PropertyChanged(this, new PropertyChangedEventArgs(sender.GetType().ToString())), null);

                }
               
            }

------解决方案--------------------
探讨
引用:

C# code


//用循环把xzdl这个UserControl找到下面是调用的。。。
http = new HttpLoadFile(Urll, 2);
http.Bname();
xzdl.DataGrid1.ItemsSource = http.List;
http.DownLoad();
我第二次是这么调用的。。。
这么用的时候数据棒的是……

------解决方案--------------------
在wpf中可以使用UI控件的Dispatcher跳转至UI线程中,达到对UI的修改,可参考如下代码。
C# code

public partial class MainWindow : Window
    {
        private int i = 0;
        private ObservableCollection<User> usrList = new ObservableCollection<User>();

        public MainWindow()
        {
            InitializeComponent();
            this.datagrid.ItemsSource = usrList;

            Thread thread = new Thread(new ThreadStart(Process));
            thread.Start();
        }

        void Process()
        {
            while (i++ < 10000)
            {
                Action action = () =>
                {
                    usrList.Add(new User(i.ToString(), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fffffff")));
                    textshow.Text = string.Format("当前共产生{0}条数据", i.ToString());
                };
                this.Dispatcher.BeginInvoke(action);
                Thread.Sleep(10);
            }
        }
        
    }