I've been attempting to create a task that writes to a database without blocking the UI thread. The biggest problem I'm having is waiting for that process to finish without the blocking happening.
I've been trying to avoid using DoEvents
(though it's used quite frequently through this program right now, I'd like to move out of using it while moving forward).
I've attempted to create the process to run on a 2nd thread and waiting for it to finish as well as using a BackgroundWorker
.
The problem I have with this is not having the code run in a different thread, but trying to find a way to wait for it to finish.
Basically, Right now I do the following:
BackgroundWorker
so I can use the ReportProgress
BackgroundWorker
BackgroundWorker
to finish. For the thread, I wait for IsAlive
to become false, for the BackgroundWorker
, I toggle a boolean variable.The problem is in #4.
Doing a while loop with no code in it, or a Thread.Sleep(0)
leaves the UI blocked (Thread.Sleep(0)
makes the program take 100% of the program resources as well)
So I do:
while (!thread.IsAlive)
Thread.Sleep(1);
-or-
while (bProcessIsRunning)
Thread.Sleep(1);
which blocks the UI.
If I call Application.DoEvents()
there, the UI is updated (though it's clickable, so I have to disable the entire form while this process runs).
If I run the process synchronously, I still need to create some sort of way for the UI to be updated (in my mind, a DoEvents
call) so it doesn't appear locked up.
What am I doing wrong?
C# uses an event model -- what you want to do is dispatch the process that does the work and then have that process fire a custom event when done or use one of the threading events. While the process is running in the "background" release control back to the system from your code.