0

How can you update the GUI when using a delegate function as new Thread? I am trying to update a label, that would tell the user the state of application's progress, but this way, it only updates once it is done, not while doing it.

public partial class Form1 : Form
{
        private void button1_Click_1(object sender, EventArgs e)
        {
            new Thread(new ThreadStart(delegate()
            {
                int currentFile= 0;
                int allFiles = Source.FilePaths.Count;
                foreach (var path in Source.FilePaths)
                {
                    var file = new File(path, Source.DestDirPath, System.IO.File.ReadAllLines(path));

                    file.saveSQL();

                    currentFile++;

                    int rounded = (int)((currentFile/ allFiles) * 100);

                    CompletionLabel.Invoke(new MethodInvoker(() => Completion.Text = "Completion: " + rounded + "%"));

                }
            })).Start();
        }
}

I would like to keep it as simple as possible, because it is just a simple converter, that converts some text file to sql files.

Ralt
  • 2,084
  • 1
  • 26
  • 38
szab.kel
  • 2,356
  • 5
  • 40
  • 74

1 Answers1

0

No, your problem is with integer division. To fix it you just need a cast to double or float. If you noticed my first comment, you'd have got the answer.

int rounded = (int)(((double)currentFile/ allFiles) * 100);

When you divide two integers, the result is always an integer. For example, the result of 7 / 3 is 2. To determine the remainder of 7 / 3, use the remainder operator (%). To obtain a quotient as a rational number or fraction, give the dividend or divisor type float or type double. You can assign the type implicitly if you express the dividend or divisor as a decimal by putting a digit to the right side of the decimal point, as the following example shows

From msdn

Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
  • When you commented the answer, I tried it in an online c# compiler, but I thought I used the (double) conversion too, so I copied your version. :) Thanks anyway! – szab.kel Aug 13 '14 at 15:47