C#: Two forms, one is calling the other one
I have a problem like this, I have two Winforms, f1 and f2.
f1 will start a loop on开发者_如何学JAVA button click, this loop checks a condition and decide to call the other form which is f2 or not.
The problem is, the loop may call f2 many times, so each time the other form f2 will be called the first form f1 should pause its execution.
So, I solved it like this, I used backgroundWorker + AutoResetEvent. I placed the backgroundWorker in the first form and inside the DoWork event handler I called f2.Show() then I called WaitOne on the AutoResetEvent let it be A.
In the other form "f2", on Exiting button I called Set on the same A.
But, unfortunately f2 got freezed when clicking that button in f1, what should I change??
Instead of dealing with threads and reset events, why not simply call the form F2 as a dialog?
var f2 = new Form2();
// ...
f2.ShowDialog(this);
This way the process on F1 will only continue after the form2 is done.
You should not halt execution on the GUI thread in WinForms, so that is likely what you are doing wrong, (ie. calling WaitOne, which will block your GUI).
Forms themselves does not do any "work" as such. They just run a message loop, waiting for input and rendering UI. You should separate your workload from your UI, and run them on a separate thread. You are already working on a background thread with BackgroundWorker, so the only change is that you should not do any blocking operation on the GUI thread.
In fact, perhaps your solution will be to use f2.ShowDialog instead of f2.Show. ShowDialog will wait until the form is dismissed, but in a way that allows the UI to keep pumping messages.
Other than that, we need to see some code to guide you further.
精彩评论