简体   繁体   中英

How to skip System.InvalidOperationException when application running on C#?

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?

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.

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