C # - code processing order - strange behavior

I have the following button click event:

private void btnRun_Click(object sender, EventArgs e) { label1.Visible = true; if (SelectDatabase()) { if (string.IsNullOrEmpty(txtFolderAddress.Text)) MessageBox.Show("Please select a folder to begin the search."); else { if (cbRecurse.Checked == false || Directory.GetDirectories(initialDirectory).Length == 0) { CheckSingleFolder(); } else { CheckSingleFolder(); directoryRecurse(initialDirectory); } } } } 

In fact, it performs a few checks and then runs a directory recursion looking for specific files. However, the very first line of code to make a shortcut visible does not happen until the directories are returned? Does anyone know why this would be?

Thanks.

+6
c # winforms
source share
5 answers

You are doing everything related to the user interface thread, which is a very bad idea - the user interface does not update, does not respond to events, etc., until you finish.

You should use the background thread and update the user interface with progress, etc. using Control.BeginInvoke , or perhaps use BackgroundWorker .

Basically, there are two golden rules in WinForms (and similar to WPF / Silverlight):

  • Do not do anything that can take a significant amount of time in the user interface thread.
  • Do not touch user interface elements from any stream other than the user interface stream.
+8
source share

your whole method works like a blocking block at present - add Application.DoEvents() as a workaround, but in fact you should do this kind of processing in the background thread, i.e. using the working background.

+1
source share

The code runs in the same thread that your user interface draws. Therefore, while the code is executing, your user interface does not redraw. After the button code is completed, the user interface will be redrawn and label1 will be drawn invisibly.

You can move your code to a separate thread using, for example, Task or BackgroundWorker . However, you cannot directly configure user interface properties from another thread, so you need to either be careful to set your user interface properties from the user interface thread, or see this question on how to update the GUI from another thread.

+1
source share

The view is not updated until the code completes. Therefore, I would suggest BackgroundWorker for the recursive part.

+1
source share

Explanation: The shortcut is set to visible, and it is invalid (redrawing is required), but the Windows message pump does not start repainting until it starts. This way your code blocks it.

A simple solution is to call label1.Update() immediately after it is visible.

The best solution is to move the time-consuming code to a thread (Backgroundworker).

+1
source share

All Articles