From HashVB
Jump to: navigation, search
 This article is based on Visual Basic 6. Find other Visual Basic 6 articles.
 For information on multithreading in Visual Basic.NET, see .NET Threading.

The easiest way to do multithreading in VB is to make use of ActiveX EXEs and "out of process" components.

Out of process COM Objects

When you have an ActiveX EXE set to "Thread per object", every object instantiated will be in a new thread in the EXEs process and all calls/events marshalled across the thread boundary. This ONLY applies when the object is created through the normal COM calls (CreateObject). If you use Set Variable = NewObject then VB will bypass all the COM stuff and create it internally, in the same thread.

So, you now have this object successfully in another thread. Lets make a call into it to do something. Oh. Your original code is still blocked while calling this other thread. This is perfectly normal and allows you to get the return value (This is called the thread of execution and has nothing to do with multi threading)

If you want to allow the main process to continue, you will need to exit from the "DoSomething" method and all it to continue. But this leaves you without any code running in your new thread....

This is where SetTimer() comes in useful with a few tricks to be able to call another method in your object allowing both to continue as normal. You can then use normal COM calls to communicate between the threads. Please note that if you have an long process running, you will need to call DoEvents periodically to allow calls to be processed.

CreateThread() and VB

You may have heard that CreateThread() is "Bad" in VB? :)

It is possible to use BUT it requires a lot of work setting up Thread Local Storage (TLS) before you do anything else. Without TLS, VB won't do much beyond beep and crash. Even after setting up the TLS, you will need to handle thread synchronisation yourself.

I will leave the details for later (or for someone else to fill in)

Enjoy :)