Stéphanie Autire
Stéphanie Autire

Reputation: 129

My UI get frozen while I add each line of a text file in a List

My UI get frozen while I add each line of a text file in a List.

This is my current code :

private void LoadProxies_Click(object sender, EventArgs e)
{
    OpenFileDialog dialog = new OpenFileDialog();

    dialog.Title = "Select your Proxies file";
    dialog.Filter = "Text File|*.txt";

    DialogResult result = dialog.ShowDialog();

    if (result == DialogResult.OK)
    {
        int list = proxiesList.Count;

        Parallel.ForEach(File.ReadLines(file), line =>
        {
            if (line != null && line.Contains(":"))
            {
                proxiesList.Add(line);

                list++;

                InvokeUI(() => { Proxies.Text = list.ToString(); });
            }
        });
    }
}

This is the InvokeUI method :

private void InvokeUI(Action a)
{
    BeginInvoke(new MethodInvoker(a));
}

I tried using Parallel.ForEach(File.ReadLines(file), line => ... and await Task.Factory.StartNew(() => ... but it's not fixing my problem.

How can I solve this ? Thanks.

Upvotes: 0

Views: 50

Answers (1)

user585968
user585968

Reputation:

My UI get frozen while I add each line of a text file in a List

The problem with your code is that it is a rather tight loop and if the file is large the following line will be called a great deal of times per second:

BeginInvoke(new MethodInvoker(a));

This would result in the Windows Message Pump being flooded with update UI requests.

A better action is to either:

  1. Since all you are doing is trying to display the numeric value of list on screen, consider updating say once a second by way of a Windows Forms timer rather than calling BeginInvoke

  2. If you must update from a worker thread, don't BeginInvoke for each item, consider updating in batches. In this case perhaps update every 100

Alternatively you may want to consider TPL DataFlow

Upvotes: 2

Related Questions