TheAnonyMoose1234512
TheAnonyMoose1234512

Reputation: 169

Thread safe invoke on functions with parameters

I'm trying to start a new thread that sorts a multiple lists and then sets the data in the rich textbox to the time elapsed while sorting.

The code I have for this is:

delegate void TextCallback(string data);
private void button1_Click(object sender, EventArgs e)
    {
        List<List<int>> data = new List<List<int>>();

        for(int i = 0; i < 8; i++)
        {
            data.Add(new List<int>());
        }
        Random rand = new Random();

        for(int j = 0; j < 1000000; j++)
        {
            foreach(var l in data)
            {
                l.Add(rand.Next(0, 10000));
            }
        }

        Thread singleThreaded = new Thread(() => doSortOnMultiList(data));
        singleThreaded.Start();

    }
    private void doSortOnMultiList(List<List<int>> lists)
    {
        Stopwatch s = new Stopwatch();
        s.Start();

        foreach(var list in lists)
        {
            list.Sort();
        }

        s.Stop();

        //SetTextBox2(richTextBox2.Text + "Single-Threaded sort: " + s.Elapsed.Milliseconds);
        SetTextBox2("Single-Threaded sort: " + s.Elapsed.Milliseconds + "ms." + System.Environment.NewLine);
    }
    private void SetTextBox2(string data)
    {
        if (richTextBox2.InvokeRequired)
        {
            Invoke(new TextCallback(SetTextBox2), new object[] { data });
        }
        else
            //richTextBox2.Text = data;
            richTextBox2.Append(data);
    }

I am using the msdn documentation and it says that the above way to do it is thread safe and will allow my program to set the text within my thread. This however is not the case as I am receiving the following error:

Cross-thread operation not valid: Control 'richTextBox2'

The only thing that is different in my implementation (from what I can see) is that I start the thread with a lambda so that I am able to pass in my lists. I must not be grasping some concept in threading so any help would be appreciated.

Here is the MSDN resource im currently using: MSDN

EDIT: I fixed the above code, old lines are commented out to show anyone after me how it differs.

Upvotes: 0

Views: 93

Answers (1)

interceptwind
interceptwind

Reputation: 675

You called doSortOnMultiList() on a separate thread,

Thread singleThreaded = new Thread(() => doSortOnMultiList(data));
singleThreaded.Start();

and within this doSortOnMultiList(), there is

SetTextBox2(richTextBox2.Text + "Single-Threaded sort: " + s.Elapsed.Milliseconds);

and within this line, there is

richTextBox2.Text

So basically, you are accessing a UI component richTextBox2 from a non-UI thread, which causes this error.

Upvotes: 2

Related Questions