-2

I'm trying to get a big string text array from a TextBox where lines are string[].

It works but the problem is that with big amounts of data in input the GUI of program is frozen for a moment while it processes the entire size of the array (differently from async functions which don't let GUI to lag). To avoid the freeze? I'm trying to use parallel for but the result seems the same... How can I fix this?

string[] text = textBox.Lines;

if (textBox.Lines.Length > 0)
{
    Parallel.For(0, textBox.Lines.Length, x =>
    {
        text[x] = textBox.Lines[x];
    });
}

FIXED:

string[] text = textBox.Lines;

if (text.Length == 0)
{
    MessageBox.Show("Insert lines", "Error");
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Programmer
  • 103
  • 1
  • 9
  • 2
    Have you tried replacing all of that code with `string text[] = textBox.Lines;`? – mjwills Jul 29 '18 at 23:11
  • Possible duplicate of [Does Parallel.ForEach Block?](https://stackoverflow.com/questions/10153729/does-parallel-foreach-block) – mjwills Jul 29 '18 at 23:12
  • Omg you're right, it's not necessary that loop.... Thanks all for helping me – Programmer Jul 29 '18 at 23:26
  • It's really very very unlikely that you have enough lines in `textBox.Lines` to make using `Parallel.For` worthwhile anyway. There's a lot of overhead to creating/using threads. You need very CPU intensive code to make it worthwhile. – Enigmativity Jul 30 '18 at 00:35

1 Answers1

3

The problem is that you are using the TextBox.Lines property in your loop. You don't need to do this at all as the Lines property recreates a new string array each time it's accessed. Just get the Lines property, and you're done. You don't need to copy it line-by-line on the UI thread.

 string[] text = textBox.Lines; //Done.

To validate that it works as I describe, look at the source: https://referencesource.microsoft.com/#system.windows.forms/winforms/managed/system/winforms/TextBoxBase.cs,37cabfde1449b18f,references

MineR
  • 2,144
  • 12
  • 18