在后台工作线程中使用对控件的引用是否安全?
假设我有一本控件和字符串的字典。如果我运行后台工作程序,使用控件引用访问与控件对应的字符串是否是线程安全的?
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];
}
这应该没问题,因为我没有使用任何控件的属性 - 我只是使用控件的引用,对吧?
Let's say that I have a dictionary of controls and strings. If I run a background worker, is it thread safe to use the control reference to access the string corresponding to the control?
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];
}
This should be OK because I am not using any of the controls' properties - I am just using the control's reference, right?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,只要您不访问控件的属性或方法,它就是完全安全的。它只是一个对象引用,它指向一个控件这一事实并不重要......
As long as you don't access properties or methods of the control, yes, it's perfectly safe. It's just an object reference, the fact that it points to a control doesn't matter...
您唯一需要确定的是 Persist 和 GetControlName 不能同时调用。
The only thing that you have to be sure, is Persist and GetControlName must not be called at same time.