2011-11-27 74 views
1

我有以下代码:绑定:工作线程改性性能

class Customers : BindableObject 
{ 

    private ObservableCollection<string> _Products = new ObservableCollection<string>(); 

    public ObservableCollection<string> Products 
    { 
     get 
     { 
      return _Products; 
     } 
     set 
     { 
      _Products = value; 
      RaisePropertyChanged("Products"); 
     } 
    } 

    private string _Name = "John"; 

    public string Name 
    { 
     get 
     { 
      return _Name; 
     } 
     set 
     { 
      _Name = value; 
      RaisePropertyChanged("Name"); 
     } 
    } 


    public Customers() 
    { 
     Products.Add("George"); 
     Products.Add("Henry"); 
    } 

    public void LongRunningFunction() 
    { 
     Name = "Boo"; 

     Thread.Sleep(5000); 

     Name = "Peter"; 

    } 

    public void ThreadedLongRunningFunction() 
    { 
     Task t = new Task(new Action(LongRunningFunction)); 
     t.Start(); 

    } 


    public void LongRunningFunctionList() 
    { 
     Products.Add("Boo"); 

     Thread.Sleep(5000); 

     Products.Add("Booya"); 

    } 

    public void ThreadedLongRunningFunctionList() 
    { 
     Task t = new Task(new Action(LongRunningFunctionList)); 
     t.Start(); 

    } 

} 

BindableObject实现INotifyPropertyChanged。

然后我在我的MainWindow.xaml.cs

public partial class MainWindow : Window 
{ 

    Model.Customers c = new Model.Customers(); 

    public MainWindow() 
    { 
     InitializeComponent(); 

     gridToBindTo.DataContext = c; 
    } 

    private void cmdRun_Click(object sender, RoutedEventArgs e) 
    { 
     c.LongRunningFunction(); 
    } 

    private void cmdRunAsync_Click(object sender, RoutedEventArgs e) 
    { 
     c.ThreadedLongRunningFunction(); 
    } 

    private void cmdRunListSync_Click(object sender, RoutedEventArgs e) 
    { 
     c.LongRunningFunctionList(); 
    } 

    private void cmdRunListAsync_Click(object sender, RoutedEventArgs e) 
    { 
     c.ThreadedLongRunningFunctionList(); 
    } 

} 

我的主窗口上绑定了名称标签,并绑定到产品列表框。

在这两个函数的线程版本中,我不明白为什么我允许在另一个线程中绑定到UI的属性'Name'(字符串)上操作,但我不允许为ObservableCollection做同样的事情。

有人可以解释为什么这里有区别吗?

问候

+0

集合不是线程安全的。 – SLaks

+0

尝试使用'Dispatcher'将更改从其他线程推送到UI – sll

+0

您可以发布绑定代码吗? – BFree

回答