Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 790
FerX32 Avatar asked Jan 16 '23 07:01

FerX32


2 Answers

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);
    }
}
like image 136
Roman Starkov Avatar answered Feb 07 '23 18:02

Roman Starkov


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;  
}  
like image 44
Mayank Avatar answered Feb 07 '23 17:02

Mayank