Of course
DoEvents
as it is used in this code is a very bad thing. Generally, the cases where this method can be used are very rare, and reliability is much concerned. In the sample you show it is attempted to use to imitate some kind of "parallelism", which never works well.
You need to do the whole operation in a separate thread. As you need to update UI while the thread is progressing, you can use UI thread invocation.
You cannot call anything related to UI from non-UI thread. Instead, you need to use the method
Invoke
or
BeginInvoke
of
System.Windows.Threading.Dispatcher
(for both Forms or WPF) or
System.Windows.Forms.Control
(Forms only).
You will find detailed explanation of how it works and code samples in my past answers:
Control.Invoke() vs. Control.BeginInvoke()[
^],
Problem with Treeview Scanner And MD5[
^].
See also more references on threading:
How to get a keydown event to operate on a different thread in vb.net[
^],
Control events not firing after enable disable + multithreading[
^].
[EDIT #1]
See also my two answers of thread wrappers:
How to pass ref parameter to the thread[
^],
change paramters of thread (producer) after it started[
^].
[EDIT #2]
And also this article:
Simple Blocking Queue for Thread Communication and Inter-thread Invocation[
^].
—SA