Your idea is quite good.
You are missing one thing unrelated to pausing, but related to UI thread. You should not manipulate objects added to currently running UI added to it in UI thread. You try to do it in your additional non-UI thread, and this is bad cross-thread operation. 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:
.NET event on main thread,
How to get a keydown event to operate on a different thread in vb.net,
Control events not firing after enable disable + multithreading.
In addition to that, you should exclude the possibilities of modifying the state of your control from two threads in some random manner. In particular, you should not update the
Nodes
from UI events directly while the loop is traversing the set of nodes. Combined with your pausing feature, which is itself is quite correct, it may lead to a bit too complicated thread synchronization schema you should study theoretically very accurately (such problems are undetectable using the usual debugging method, no testing methods at all). That said, I would consider the whole problem in a holistic manner and probably think about total redesign of your code. At this moment, I cannot advise anything certain, because I don't know your ultimate goals.
One more note. Never ever use names like
treeview1
,
btn_pause_Click
or any other auto-generated names. They violate (good) Microsoft naming conventions (authors of automatic code generation simply had no choice) and makes no sense. Names should be semantically sensible. You are supposed to rename every auto-generated name using the refactoring engine, which makes is easy. Also, it's a matter of some discussion, but I usually advice not to generate any event handlers in the designer. The code generated for adding such handlers is ugly and even obsolete.
—SA