What are you doing?! You code uses the same method on one non-UI thread and also the same method is to be called on button click and run on UI thread. It cannot be what you need.
Most likely, you need to start non-UI thread by the button click. There are different ways of doing this. You can call
Thread.Start
. Better yes, you can keep the thread in the wait state at some
EventWaitHandle
, and the button will call
EventWaitHandle.Set
to let the thread go as soon as there is a "task" for this thread (expressed as some data). More regular way of doing that is using blocking queue to feed data to the thread, or some delegate instances representing thread tasks. See my Tips/Trick article on complete code, code samples and more detailed explanation:
Simple Blocking Queue for Thread Communication and Inter-thread Invocation[
^].
Alternatively, you can
System.ComponentModel.BackgroundWorker
and start it by your button click. For a regular thread, I recommend using thread wrapper I offered here:
How to pass ref parameter to the thread[
^].
Now, remember, you can never use UI object directly from non-UI thread. Instead, you need to use
Invoke
or
BeginInvoke
methods of
System.Windows.Forms.Control
or
System.Threading.Dispatcher
classes (the
Dispatcher
can work with both
Forms
and WPF. See for more detail:
Control.Invoke() vs. Control.BeginInvoke()[
^].
Basically, invocation mechanism gets delegate instances and all data needed for a call, put in a queue and this queue is later accessed by the UI thread (in its
Application.Run
main cycle) to perform the actual call in UI thread.
Sorry, many references explain the techniques without code, but some code samples are in C#. Please understand, to get good help or code samples on .NET you need to know at least some C#; you cannot get so much help in VB.NET along.
You can also use available C# code the way which does not require C# programming skills: make a separate class library project out of it and reference in your VB.NET project. For .NET the boundary between languages does not exist!
—SA