//I want to start a thread that set postion of a la lable here is part of the code

     t = new Thread(bar);

            t.Start();

public void bar()
        {
            while (true)
            {


                label2.Location = new Point(this.label2.Location.X + 10, this.label2.Location.Y);
                Thread.Sleep(1000);
                if (this.label2.Location.X > this.Width)
                {
                    label2.Location = new Point(200-this.label2.Width + 10, this.label2.Location.Y);
                }
            }
        }

//here is the problem
//Invalid cross-thread operation: Control 'Form1' has been accessed from a thread other than the one on which it was created.

You can only update controls on the thread that created them. Your new thread isn't that thread so you have to Invoke the controls

As Momerath said, you'll need to Invoke the control if you want to update a control from a thread other than the UI thread, however one alternative (depending on what work you're wanting to do in this other thread) may be to simply launch the function that does the work asynchronously.

instead of

public void MyUIFunction()
{
    Thread t = new Thread( new ThreadStart( bar ) );
    t.Start();
}

public void bar()
{
    txtOuput.Text += "OutputText";
}

try

public void MyUIFunction()
{
    bar();
}

public async Task bar()
{
    txtOuput.Text += "OutputText";
}

See http://msdn.microsoft.com/en-us/library/hh191443.aspx for more information

Don't you need delegate void for this? like this:

public delegate void ControlLocation(Control control, Location loc); 

public void SetLocation(Control control, Location loc) {
    if (control.InvokeRequired) {
        control.Invoke(new ControlLocation(SetLocation), new object[]{control, loc}); 
    } else {
        control.Location=loc;      
    }
}

Or am I mistaken?

SynThiicQ, that would be invoking which is the solution Momerath offered. With my example you do not need to invoke manually as the .NET framework takes care of it for you (:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.