正在使用对后台工作线程安全中的控件的引用

本文关键字:安全 控件 引用 线程 工作 后台 | 更新日期: 2023-09-27 18:13:27

假设我有一个控件和字符串的字典。如果我运行一个后台工作,它是线程安全使用控件引用访问对应于控件的字符串吗?

Dictionary<Control, string> _ctlDict;
//Called in the main thread
public void Persist()
{
  foreach (var control in Controls)
  {
    _ctlDict.Add(control, control.Name);
  }
}
//Called in the background worker
public string GetControlName(Control ctl)
{
  return _ctlDict[ctl];
}

这应该是OK的,因为我没有使用任何控件的属性-我只是使用控件的引用,对吗?

正在使用对后台工作线程安全中的控件的引用

只要您不访问控件的属性或方法,是的,它是完全安全的。它只是一个对象引用,它指向控件的事实并不重要…

唯一需要确定的是,Persist和GetControlName不能同时被调用