Question

 private void btnCount_Click(object sender, EventArgs e)
    {        
        Thread thread = new Thread(FuncX);
        thread.Start();         

        FuncY();
    }

    public void FuncX()
    {
        this.Invoke(new MethodInvoker(delegate
        {
            //put UI thread code here.
            //you can assign local variables values from the main thread in here as well. They are both accessible.
            lblThreadDisplayX.Text = "0";
            int x = Convert.ToInt32(lblThreadDisplayX.Text);
            for (int j = 0; j < loopTime; j++)
            {
                x++;
                lblThreadDisplayX.Text = x.ToString();
                Thread.Sleep(5);
                Update();
            }
        }));           
    }

    public void FuncY()
    {
        lblThreadDisplayY.Text = "0";
        int y = Convert.ToInt32(lblThreadDisplayY.Text);
        for (int i = 0; i < loopTime; i++)
        {
            y++;
            lblThreadDisplayY.Text = y.ToString();
            Thread.Sleep(5);
            Update();
        }
    }
}
}

Above is my code for a tester I'm working on to get threading to work. There are 2 labels, X and Y, which call functions X and Y, and in those functions, the text of the labels are incremented by 1 repeatedly. However, I want to do this simultaneously. When I try to make a thread out of FuncX, it says that it cannot access an object created in another Thread and crashes. I used the lock(){} statement, but it didn't work. What can I do to have the label's text change inside of a thread?

Edit: Updated the Code, and this is with a Windows Form in Visual Studio 2008. Adding in a Timer to the thread with FuncX in it causes FuncY to execute first, then FuncX's thread.

Was it helpful?

Solution

Your problem is twofolde:

1- should not be sharing controls or variables between threads without looking at locking them first. You are technically in a Race Scenario at that point which can cause havoc.

2- The labels were created on the Main UI thread. In order to access them from within a thread, you have to Invoke the main thread to get at it, from within your sub threads... which, again, circumvent the whole point of threading since you're also using the labels to "globally store your variables".

But if you must, here's how to access the labels within your threads:

To execute code from within the thread or access elements:

this.Invoke(new MethodInvoker(delegate
{
    //put UI thread code here.
    //you can assign local variables values from the main thread in here as well. They are both accessible.
}));

To only extract the value of an object or property of an object (i inserted placeholders for you here, this call is not a literal call and you must adapt it to your needs):

TypeName yourvar = (TypeName)this.Invoke(new Func<TypeName>(() => UICode here as TypeName));

Hope this helps you!

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