更新:现在使用基于以下评论的只读集合
我相信下面的代码应该是线程安全的"锁定免费"代码,但是要确保我没有遗漏某些东西......
public class ViewModel : INotifyPropertyChanged
{
//INotifyPropertyChanged and other boring stuff goes here...
private volatile List<string> _data;
public IEnumerable<string> Data
{
get { return _data; }
}
//this function is called on a timer and runs on a background thread
private void RefreshData()
{
List<string> newData = ACallToAService();
_data = newData.AsReadOnly();
OnPropertyChanged("Data"); // yes, this dispatches the to UI thread
}
}
Run Code Online (Sandbox Code Playgroud)
具体来说,我知道我可以使用一个lock(_lock)甚至是一个Interlocked.Exchange()但我不相信在这种情况下需要它.volatile关键字应该足够(以确保不缓存该值),不是吗?有人可以确认一下,或者让我知道我对线程的理解不清楚:)