加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#线程安全(特别是MVVM / WPF)

发布时间:2020-12-16 00:04:08 所属栏目:百科 来源:网络整理
导读:我想知道我需要做些什么来使MVVM中的模型线程安全.假设我有以下类,它被实例化为单例: public class RunningTotal: INotifyPropertyChange{ private int _total; public int Total { get { return _total; } set { _total = value; PropertyChanged("Total")
我想知道我需要做些什么来使MVVM中的模型线程安全.假设我有以下类,它被实例化为单例:

public class RunningTotal: INotifyPropertyChange
{
   private int _total;
   public int Total
   {
      get { return _total; }
      set
      {
         _total = value;
         PropertyChanged("Total");
      }
   }
   ...etc...
}

我的视图模型通过属性公开它:

public RunningTotal RunningTotal { get; }

我的视图有一个绑定它的文本块,即{Binding Path = RunningTotal.Total}.

我的应用程序有一个后台线程,定期更新Total的值.假设没有其他任何更新总计,我应该做什么(如果有的话)使所有这些线程安全?

现在,如果我想做类似的事情,但使用Dictionary<>,或ObservableCollection<>?类型的属性,该怎么办?哪些成员(添加,删除,清除,索引器)是线程安全的?我应该使用ConcurrentDictionary吗?

解决方法

My app has a background thread that periodically updates the value of Total. Assuming nothing else updates Total,what (if anything) should I do to make all this thread-safe?

对于标量属性,您不需要做任何特殊的事情; PropertyChanged事件自动封送到UI线程.

Now,what if I wanted to do something similar but using a property of type Dictionary<>,or ObservableCollection<>? Which members (add,remove,clear,indexer) are thread-safe? Should I use a ConcurrentDictionary instead?

不,这不是线程安全的.如果您更改ObservableCollection的内容< T>从后台线程,它将打破.您需要在UI线程上执行此操作.一种简单的方法是使用一个在UI线程上引发事件的集合,如here所述.

对于Dictionary< TKey,TValue>,当其内容发生变化时,它不会发出通知,因此无论如何都不会通知UI.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读