I user a couple of extension methods for this.
public static class ControlExtensions
{
public static void SafeInvoke(this Control control, Action action)
{
if(control.InvokeRequired)
{
control.BeginInvoke(action);
}
else
{
action();
}
}
}
and then to use it, something like this.
public void TreeCompleted(bool completed)
{
this.SafeInvoke(() =>
{
if(completed)
{
DiagnosisTree = treeBranchControl1.GetDiagnosisTree(null);
pctLoader.Visible = false;
btnSelectDiagnosis.Visible = false;
lblDiagnosis.Visible = true;
treeBranchControl1.Visible = true;
}
else
{
DiagnosisId = 0;
DiagnosisTree = null;
}
});
}
this is the form or control where the code is running.
In your case, you do do this:
public void SetText(string text, int i)
{
this.SafeInvoke(() =>
{
switch (i)
{
case 1:
this.label1.Text = text;
break;
case 2:
this.label2.Text = text;
break;
}
});
}