Thread-Safe is not Multithreaded...

  • Thread starter Thread starter Frank Uray
  • Start date Start date
F

Frank Uray

Again hi all

I have seen another problem...
I have tried to make some procedures multithreaded,
and it works fine if I for example fill a TestBox from
the threads.
As soonest I try to fill up a treeview, I get the message
that this is not allowed from another thread, I have to
make it thread-safe.
So far so good, I made a delegate and it works BUT
it is not multithreaded any more!!!
It looks like the application is waiting until the
execution of the delegated thread is finished...:-((

What am I doint wrong??

Thanks for any replay
Frank

Here is the code of it:

Private Sub Thread4_TS()
Dim theDL As New Thread4_Delegate(AddressOf Me.Thread4)
Me.Invoke(theDL)
End Sub

Delegate Sub Thread4_Delegate()

Private Sub Thread4()

Dim MyNode As New System.Windows.Forms.TreeNode("This is a
node")
Me.TreeView1.Nodes.Add(MyNode)

Dim MyShow As New Class2()
MyShow.ShowMessage(Me.TextBox1, "Thread4:")

End Sub
 
Frank Uray said:
I have seen another problem...
I have tried to make some procedures multithreaded,
and it works fine if I for example fill a TestBox from
the threads.
As soonest I try to fill up a treeview, I get the message
that this is not allowed from another thread, I have to
make it thread-safe.
So far so good, I made a delegate and it works BUT
it is not multithreaded any more!!!
It looks like the application is waiting until the
execution of the delegated thread is finished...:-((

And indeed it is. Invoke() waits until the call has finished. If you
want asynchronous execution, you need to use BeginInvoke and EndInvoke.
 
Hi Frank,
You cannot update UI from a thread different than the one created the
control you want to update. This is true for all controls and even if you
*can* update the textbox you has to avoid this (in some cases it might not
work).

What you have to do if you want to update (say a TareeView) control from
different thread is:
1. Start a new worker thread that will produce the data you want to show on
the tree.
2. Call a delegate using Control.Invoke. As a control use reference to the
form hosting the TreeView or the TreeView itself. Pass all data produced by
the worker thread and necessary to create the tree-view node.
3. In the delegate's target method update the tree view.

What does Control.Invoke do? It executes the delegate in the context if the
main UI thread. The worker thread stays blocked in Invoke method until
delegate finishes its work. Because the delegate is executed in the main
thread during execution of the delegate no other events are processed.

In your example there is no benefit of using a worker thread. But if
producing data for the nodes is time consuming (like reading data from a DB,
Internet, etc) using worker thread will keep the UI alive. You switch the
thread only to add already produced data to the tree view ( this is cheap
operation).

HTH
B\rgds
100
 
Back
Top