views:

184

answers:

1

Hey guys,

In my app, i have an import option, to read info from a .csv or .txt file and write it to a database. To test, i"m just using 200-300 lines of data. At the beginning of the method, i calculate number of objects/lines to be read. Every time an object is written to the database, i want to update my progressbar. This is how i do it :

private void Update(string path)
    {
        double lines = 0;
        using (StreamReader reader = new StreamReader(path))
            while ((reader.ReadLine()) != null)
                lines++;
        if (lines != 0)
        {
            double progress = 0;
            string lijn;
            double value = 0;
            List<User> users = new List<User>();
            using (StreamReader reader = new StreamReader(path))
                while ((line = reader.ReadLine()) != null)
                {
                    progress++;
                    value = (progress / lines) * 100.0;
                    updateProgressBar(value);
                    try
                    {
                        User user = ProcessLine(lijn);
                    }
                    catch (ArgumentOutOfRangeException)
                    { continue; }
                    catch (Exception)
                    { continue; }
                }
            return;
        }
        else
        {
           //non relevant code
        }
    }

To update my progressbar, i'm checking if i can change the ui of the progressbar like this :

delegate void updateProgressbarCallback(double value);

private void updateProgressBar(double value)
    {
        if (pgbImportExport.Dispatcher.CheckAccess() == false)
        {
            updateProgressbarCallback uCallBack = new updateProgressbarCallback(updateProgressBar);
            pgbImportExport.Dispatcher.Invoke(uCallBack, value);
        }
        else
        {
            Console.WriteLine(value);
            pgbImportExport.Value = value;
        }
    }

When i!m looking at the output, the values are calculated correctly, but the progressbar is only showing changes after the method has been called completely, so when the job is done. That's too late to show feedback to the user.

Can anyone help me solve this.

EDIT : I'm also trying to show some text in labels to tell te user what is being done, and those aren't udpated till after the method is complete.

Thanks in advance.

+2  A: 

This would be a good place to use a BackgroundWorker (here's a link to MSDN's description of it with an example).

You can register an event handler for the ProgressChanged event (which you would raise periodically while performing the work of reading the lines).

Eric