1
private void buttonSave_Click(object sender, EventArgs e)
{
    textBox1.Text = "DATA is being copied.";

    //my own function to cpy files, working properly
    copyDirectory(sourceFolderPath, destFolderPath);
}

Copying takes 3 seconds, but i cannot see TextBox with text="DATA is being copied. before it goes into the copyDirectory function", it only updates the text box after finishing copy, what is the Problem? i am not using another thread in copying.

6
  • 3
    so you are doing all your work on the GUI thread? Commented Jan 21, 2015 at 12:30
  • 3
    "i am not using another thread in copying." <- This is the problem. As @John3136 mentions, if you don't explicitly say which thread to use, it will use the GUI thread which means no GUI updates until the function is done. Commented Jan 21, 2015 at 12:32
  • 1
    If you are in UI thread, this behavior is normal :s Commented Jan 21, 2015 at 12:32
  • 2
    Which version of .Net are you using? If 4.5 or later, you can use async to do this, otherwise you can use a BackgroundWorker. Commented Jan 21, 2015 at 12:33
  • Setting the Text property doesn't mean that your TextBox is repainted immediately with the change. You need to exit from that Event Handler to give the system the opportunity to redraw the TextBox, Or use a BackgroundWorker to execute your copyDirectory and thus exiting from the event handler Commented Jan 21, 2015 at 12:34

1 Answer 1

6

This is because of how Windows Forms handles events. Windows Forms is executing all events synchronously. Which means that when a button is clicked, all code in all attached events are executed, before anything else happens.

This means that until the copying finishes (that is, the method returns), the textbox will not be visibly updated.

There are several fixes for this. One fix is to have the button click start a timer, that executes 100 milliseconds later. And then when the timer executes, perform the copying.

Another (my preferred) would be to execute the copyDirectory method inside a Task:

Task.Factory.StartNew(() => copyDirectory(sourceFolderPath, destFolderPath))

Note: This means that the code runs on a different thread, so if you want to update the textbox to say something like "Completed!" when it's finished, you'll need to do this

Invoke(new Action(() => textbox.Text = "Completed!");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.