Simple upload / threading form

In an outdated application, we have one winform, which is blocked when the code is executed when the button is pressed ... well, it does not block it, it simply "stops responding" until the code is executed.

What is the best (smallest amount of code and working) way to wrap the code below in a separate thread and show the loading window (frmLoading) during its execution? I know this should be relatively simple, but I tried several different things that didn’t quite work.

private void btnSynch_Click(object sender, EventArgs e) { btnSynch.Enabled = false; if(chkDBSynch.Checked) PerformDBSyncronization(); if(chkAppSynch.Checked) PerformApplicationSyncronization(); btnSynch.Enabled = true; } 

EDIT: Well, I had to mention, tried a background worker, but I found out where I stumbled ... This code was executing, and the upload form got behind the main form, so I thought it didn't work. Can someone tell me how to prevent this?

  private void btnSynch_Click(object sender, EventArgs e) { btnSynch.Enabled = false; frmLoading loadingWindow = new frmLoading(); loadingWindow.Show(); BackgroundWorker bw = new BackgroundWorker(); bw.DoWork += (s, args) => { Thread.Sleep(6000); //TODO:just for testing if(chkDBSynch.Checked) PerformDBSyncronization(); if(chkAppSynch.Checked) PerformApplicationSyncronization(); }; bw.RunWorkerCompleted += (s, args) => { loadingWindow.Close(); }; bw.RunWorkerAsync(); btnSynch.Enabled = true; } 
+4
source share
2 answers

I feel stupid ... The upload form appears behind the main form, so I thought it didn’t open. I set the TopMost property to true, and everything works as expected.

Edit:
Here is a good explanation why my form appeared outside my window, I just did not expect the stream to open the window so as not to use the main form as the owner.

Why use the owner window in MessageBox.Show?

I ended up with my code similar to

  frmLoading loadingWindow = new frmLoading(); loadingWindow.Show(this); BackgroundWorker bw = new BackgroundWorker(); bw.DoWork += (s, args) => { this.Invoke(new MethodInvoker(() => this.Enabled = false)); if(chkDBSynch.Checked) PerformDBSyncronization(); if(chkAppSynch.Checked) PerformApplicationSyncronization(); }; bw.RunWorkerCompleted += (s, args) => { loadingWindow.Close(); this.Invoke(new MethodInvoker(() => this.Enabled = true)); }; bw.RunWorkerAsync(); 
+2
source

Use BackgroundWorker for this purpose.

0
source

All Articles