-3

I have used thread , task function to remove UI block after method is executing. I used following code but it gave me System.InvalidOperationException. Here is code I tried:

private void FindVariation()
{
    string[] idlist = richTextBox7.Text.Split('\n');  // < == System.InvalidOperationException
    // foreach (string id in idlist)
    for (int i = 0; i < Convert.ToInt32(idlist.Length); i++)
    {
        string url = "http://www.ebay.com/itm/" + idlist[i];
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        StreamReader sr = new StreamReader(response.GetResponseStream());
        // richTextBox2.Text += sr.ReadToEnd();
        string a = sr.ReadToEnd();
        sr.Close();
        string source = null;
        source = string.Join(Environment.NewLine,
            a.Split(',', ']', '[')
            .Where(m => m.Length == 12 && m.All(char.IsDigit)));

        if (string.IsNullOrEmpty(source))
        {
            // MessageBox.Show("String is null");
        }
        else
        {
            richTextBox6.Text += idlist[i] + Environment.NewLine;
        }
        richTextBox1.Text = richTextBox7.Text;
    }
}
Task fv = new Task(FindVariation);
fv.Start();

Could anybody show me what is the error?

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104

1 Answers1

1

Here's the kind of approach you need:

async Task Main()
{
    string input = richTextBox7.Text;
    string result = await Task.Run(() => FindVariation(input));
    richTextBox1.Text = result;
}

private string FindVariation(string richTextBox7Text)
{
    string[] idlist = richTextBox7Text.Split('\n');

    //your code - but no access to any UI element.
    
    return result;
}

The key thing is that inside the FindVariation you cannot access or update any UI element. Everything has to be passed in or passed out before UI is updated.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172