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:
- Connect to the database
- Create a background worker (or thread) to do the writing to the database (I will probably end up with the
BackgroundWorker
so I can use theReportProgress
- Start the thread or
BackgroundWorker
- Use a While loop to wait for the thread /
BackgroundWorker
to finish. For the thread, I wait forIsAlive
to become false, for theBackgroundWorker
, I toggle a boolean variable. - I let the user know the process is finished.
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?