FerX32
FerX32

Reputation: 1407

Cross-Threading, Accessing Thread other than it was created for

I am trying my hardest to learn Cross/Multi Threading, but I am very confused on the concept. I made a sample application which is suppose to display i on a label.text via a thread. it's not working because I am trying to access a thread other than it was created on, I've researched a lot and I am still confused on Invoking, Delegation, etc... Here is my code:

private void s1_Click(object sender, EventArgs e)
{
    Thread Thread1 = new Thread(new ThreadStart(Start1));
    Thread1.Start();
}

public void Start1()
{
    for (int i = 0; i < 1000; i++)
    {
        displaytext("Working.........", i);
        Thread.Sleep(100);
    }
}

public void displaytext(string thetext, int number)
{
    t1.Text = thetext + " " + number;
}

What is a good way to get this working ? Any help is greatly appreciated. I am learning this for the love of programming.

Upvotes: 4

Views: 2992

Answers (2)

Mayank
Mayank

Reputation: 8852

You gotta Invoke the function through delegate to get it to work.

private void s1_Click(object sender, EventArgs e)  
{  
    Thread Thread1 = new Thread(new ThreadStart(Start1));  
    Thread1.Start();  
}  

public void Start1()  
{  
    for (int i = 0; i < 1000; i++)  
    {  
        if(t1.InvokeRequired)
        {
             t1.Invoke(new MethodInvoker( () => displaytext("Working.........", i)));  
        }
        else
        {
             displaytext("Working........", i);
        }
        Thread.sleep(100); 
    }  
}  

public void displaytext(string thetext, int number)  
{  
    t1.Text = thetext + " " + number;  
}  

Upvotes: 2

Roman Starkov
Roman Starkov

Reputation: 61432

I am trying to access a thread other than it was created on

The actual error is accessing a Windows Forms control on a thread other than the one creating it.

The fix: use Invoke.

public void Start1()
{
    for (int i = 0; i < 1000; i++)
    {
        t1.Invoke(() => displaytext("Working.........", i));
        Thread.Sleep(100);
    }
}

Upvotes: 7

Related Questions