简体   繁体   中英

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.

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);
    }
}

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;  
}  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM