Question

I want to make thread can call window form control. I make this:

delegate void SetTextCallback(String str, int i);
private void SetText(string text, int i)
{
    // InvokeRequired required compares the thread ID of the 
    // calling thread to the thread ID of the creating thread. 
    // If these threads are different, it returns true. 
    if (this.label2.InvokeRequired)
    {
        SetTextCallback d = new SetTextCallback(SetText);
        this.Invoke(d, new object[] { text,i});
    }
    else
    {
        switch (i)
        {
            case 1:
                this.label1.Text = text;
                break;
            case 2:
                this.label2.Text = text;
                break;
        }

    }
}

But it seem too long because I want to call many form obj( label1, label2, textbox,...) -> case 1,2,3,4,5 and we will have many case.

Is there a better way? With out int i in SetText(string text, int i)

Another way

Not using switch(i) to know which obj need changing text

=====update=====

this is the code in thread

SetText("This text for the first label",1);
SetText("This text for the second label",2);

No correct solution

OTHER TIPS

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;
        }
    });   
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top