Question

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?

Was it helpful?

Solution

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...

OTHER TIPS

The only thing that you have to be sure, is Persist and GetControlName must not be called at same time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top