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做同樣的事情。
有人可以解釋爲什麼這裏有區別嗎?
問候
集合不是線程安全的。 – SLaks
嘗試使用'Dispatcher'將更改從其他線程推送到UI – sll
您可以發佈綁定代碼嗎? – BFree