Solved

Multi-Threads in VB

Posted on 2000-04-04
32
831 Views
Last Modified: 2009-07-29
How do I make a VB Application multi-threading?? I need to do a few tasks at the same time. I have an Smart Card based application, which includes a LiveUpdate module (something like NAV LiveUpdate).

Now..if I run liveupdate, and if there are updates to the application available, the update download will take about 5 minutes. And if I put the LiveUpdate (LU) routines in a module, the application will not respond to any other events, until the LU procedure exits.

I want the application to check for updates every time it comes up (as in Form_Load or at predetermined intervals). The problem here would be that if there 'are' updates available, the users will NOT be able to use the application until LU has finished executing. So..I need to execute the LU in another thread so that the application will complete the form_load event and wait for other events (while LU executes in the background).

Dun worry about other issues such as checking for active internet connections and timed-out by LU procedure. I've already taken care of that. I just need some codes on multi-threading. I know there are some API for threads (CreateThread and TerminateThread) in 'kernel32', but how do I call them???

Can you help?? A complete AND working code would be nice. Thanks..

I'll come back and check again in a few days. This will give you 'experts' some time to apply your 'grey matter' to the task...:)
0
Comment
Question by:st_steve
  • 14
  • 12
  • 2
  • +4
32 Comments
 
LVL 6

Expert Comment

by:Marine
ID: 2685945
posting to see a reply
0
 

Expert Comment

by:anand_m
ID: 2686149
1. Go to API  text Viewer ( comes as part of Microsoft Visual Studio ) and select the API functions you need like CreateThread,etc. Copy it to the Clipboard and get back to the VB project and paste it in the .bas module.

The API call is automatically converted for you to map into VB Data Types

2. You may take a look into DoEvents function in VB which is not exactly multithreading but rather the OS allocates time chunks to each request. But this is not fully under your control and comes with some disadvantages but it works.
See the MSDN Help for this function

Anand
0
 
LVL 10

Expert Comment

by:caraf_g
ID: 2686582
CreateThread in VB is very unreliable and you are asking for stack dumps and GPFs....

Are you using VB6?
0
 
LVL 2

Expert Comment

by:sbmc
ID: 2686619
Why not create a separate ActiveX EXE which is fired up on form load and terminated on form unload. Put your LU module in the ActiveX and forget about it in your UI module. ActiveX EXE use separate threads.
0
 
LVL 1

Expert Comment

by:PatrickVD
ID: 2686773
Hi Steve,

I totally agree with caraf_g remark on using CreateThread API. Several articles and online forums have mentioned it.

Nevetheless, I have some other proposition for you.. I assume that when you are doing the LiveUpdate type of processing, you are downloading a file... Have you tought of creating this functionality into an ActiveX CONTROL. you could then use then AsyncRead functionalities to perform an asynchrounous download of the file... I assume this is the most blocking part of your processing...
0
 
LVL 10

Expert Comment

by:caraf_g
ID: 2686797
Perhaps, yes.

But if you want to implement actual multi threading you could check out this test application I wrote:

Threading without rocket science.

http://homepage.eircom.net/~carafa/TEMP/AWXB.zip

Explanation / order of compilation
AWXB02MSG.exe - (ActiveX.exe, one thread for all objects) Messaging application that will take care of sending messages between spawned threads and the main application.
AWXB01Thread.dll - The code that will be run in each separate thread
AWXB04Starter.exe - (ActiveX.exe, one thread per object) Application that will take care of creating each new thread.
AWXB03Test.exe - Standard exe. Main application / test bed.

Hope this helps
0
 
LVL 6

Author Comment

by:st_steve
ID: 2688519
Sorry for the late response guys...I checked yesterday...but I keep getting this 'internal server error' thingy...so....I'll look at all your comments and will be back in a couple of hours, ok?

anand_m:

I'll grade your answer soon..

Others:

thanks for the comments....check again in a few hrs...
0
 
LVL 6

Author Comment

by:st_steve
ID: 2688567
Ok...I looked at all your comments

anand_m:

As mentioned in my question, I know there are API for threads, but how do I 'call' them..I know VB will do auto-converts and all that stuff..but dun I have to declare anything? for example...I have written some codes to put an application icon in the 'System Tray' (now they call it something else in Win2K..I can't recall what the word is)....but I need to declare a lot of functions and data types and the calling routines. the following is an extract from my coding:

    nidTray.hwnd = lngHwnd
    nidTray.cbSize = Len(nidTray)
    nidTray.hIcon = frmTrayAS.Icon
    nidTray.szTip = strToolTip
    nidTray.uCallbackMessage = WM_CALLBACK_MSG
    nidTray.uID = lngWndID
    nidTray.uFlags = NIF_MESSAGE Or NIF_TIP Or NIF_ICON

So...this is the kind of code I'm looking for in creating threads. Please point me to the exact location in MSDN library. I've aleady looked at 'DoEvent' function, it doesn't work. I know 'doevents' has to be placed 'strategically' and I've tried...but still doesn't do what I want to accomplish. So..no offence, but I'll have to reject your proposed answer.

caraf_g:

Yes...I'm using VB6 (SP3). So..if creating threads will 'create' a lot of problems, can you think of another way to solve my problem?? I'll check the application you've written.

sbmc & PatrickVD:

Very good suggestions, only one problem, my programming skills are not at the level of creating ActiveX objects.....'yet'.... I've tried creating ActiveX DLL, and I'm still experimenting on it...and I have a few problems with its entry points. And PatrickVD, you're right about the 'asynchrounous download blocking' part. the application will literally 'hang' until the download completes. If you can help me create the ActiveX EXE as you both mentioned, that would be great. I will increase the points for this question, if necessary.

One little comment from me...I thought most Windows applications make use of threads. The most common example would be 'setup applications' where it checks the computer system, decompresses the files, copies the files and registers the components (all at the same time). How does it accomplishes all these things without threads??
0
 
LVL 10

Expert Comment

by:caraf_g
ID: 2688940
"its entry points"

Ah... No, that's not the way it works. ActiveX components don't work with "entry points" in the same way ordinary DLLs such as Kernel32.dll would.

Ordinary DLLs are used by VB through the Declare statement or a Type Library. Example:

Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

ActiveX components are used through the references. If you have a VB project that uses MyActiveX.DLL or SomeActiveX.EXE then you must go to project/references and add a reference to this component to the project.

The way you can interact with these components is NOT through function declarations, but by means of public objects. These can be classes, user controls and some other types...

After referencing, you'd typically code something like:

'To declare an object variable to use one of your ActiveX component's public classes:
Dim objSomeObjectVariable As YourActiveXComponent.SomePublicClass

'To instantiate the object
Set objSomeObjectVariable = New YourActiveXComponent.SomePublicClass

'You will have coded for public Subs, Functions and Properties in your public class. You can now start using them for the instance you just created:
Call objSomeObjectVariable.APublicSub
objSomeObjectVariable.APublicProperty = SomeValue

etc.


Anyway, my sample code gives you a couple of examples of ActiveX components. There's an ActiveX DLL and there are two ActiveX EXEs, one with a "thread per object" threading model, and one with a "thread pool" threading model.

If your programming skills are, as you say, not at the level of creating ActiveX objects yet, it's going to be tough going to get your head around them, but don't hesitate to ask further questions. It's worth persisting...
0
 
LVL 6

Author Comment

by:st_steve
ID: 2689229
Adjusted points from 100 to 110
0
 
LVL 6

Author Comment

by:st_steve
ID: 2689230

Caraf_g:

I've tried your application(s)...I first start the "AWXB02MSG" project, and when I run the Group3 project, it gives me an error (ActiveX component can't create object) in cmdStart. Any ideas?? like I said..my skills in ActiveX technology are 'non-existent'!! so..how about a step-by-step guide to using your application?? And if I can integrate 'some' of your coding in my application, the points will be yours, and I'll give you credit in my application.

I've also heard of multi-threaded ActiveXes and DLLs, what about those objects?? Are they prone to GPFs and stack overflows as well?? If they're not, then if I can create a DLL for the LU (as Symantec - NAV has done), that would be good as well.

By the way...thanks for the latest tip caraf_g. I guess I'm getting the ideas crossed with normal DLL and activeX Dll...will try your approach AND your program
0
 
LVL 6

Author Comment

by:st_steve
ID: 2689237
I'm not afraid to apply my grey matter as well..I need more than point-and-click things in my applications!! Any help would be appreciated.
0
 
LVL 10

Expert Comment

by:caraf_g
ID: 2689278
Hi Steve,

wrt VB6 - I think it is highly recommended that you have SP3. But try it without anyway, see what happens.

Because they're ActiveX components they'll need to be registered. Best way to achieve that is to open the VB projects for:

AWXB02MSG.exe
AWXB01Thread.dll
AWXB04Starter.exe
AWXB03Test.exe

in that order and re-compile them. That will register them properly.

Then, just run AWXB03Test.exe

AWXB04Starter.exe is exactly that: a multi-threaded ActiveX.EXE

VB has no in-built support for multithreaded ActiveX.dlls (Free Threading), but it does support so-called "Apartment Threading". It's a bit too complicated to describe in a thread like this... <euphemism for "I'm not too sure about this myself :o)>
0
 
LVL 6

Author Comment

by:st_steve
ID: 2689313
I do have VB6 SP3....so I'll try to recompile them and try out the applications....if they work as I would like them to be..the points will be yours..pls give me until tomolo to test it out...ok?? thanks....
0
 
LVL 10

Expert Comment

by:caraf_g
ID: 2689346
Sure! Take your time! And don't hesitate to ask further questions if anything's not clear.
0
 
LVL 6

Author Comment

by:st_steve
ID: 2691617
caraf_g:

I've looked at your application; it works great. Just two more things before I leave you alone to answer other people's questions.

1)   (I don't mean to offend you)..do you have any proof that the application is actually multi-threading?? I mean...if I incorporate my LU function, is there a definite output that will proof to me that LU is running in the background?? Me...being a Computer Science graduate, I would like to see that the 'algorithm' is actually working, you can understand that, can't you?? :}

2)   With your permission, I would like to include your sample codes in my application. Is that ok?? If it is, you'll need to tell me the codes that would need modification to suit my application AND an easier way to register (possibly automatically register) the components. I mean, when I implement the smart card application on the terminals, I do not want to go to each computer, install VB6 with SP3 and then recompile the objects, just to register them in the Registry.

Can you also point me to any sites where there are good reference materials about ActiveX objects?? I would like to learn more, and like I said before, I want my applications to use the full power(s) of both Windows and VB, not just 'click, click and click'. By the way, I DO have SP3; I think it's the latest Service Pack (3). Cost me a fortune to download it on a 31K connection as well!!

thanks again....
0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
LVL 10

Accepted Solution

by:
caraf_g earned 110 total points
ID: 2692547
Hi st_steve

1) - Mathematical proof - no, but practical, yes. Our company here has built an application based on this principle and it works fine. As a test, I put a tight loop (simply a counter from 1 to A Very Large Number) without *any* Doevents (so no yielding at all) in the thread DLL's module, and established that this ran successfully by posting messages on the "message queue" executable which were then monitored by the calling application. The messages appear in a monitor screen in a nearly random order which proves that all threads are running concurrently. Obviously, though, my machine is an ordinary PC with a single processing so what I perceive as concurrent execution is really time-slicing by the Windows operating system. But it's as multi-threading as any other multi-threading solution you'll get on a single processor PC.

2) Of course! You are free to use my code and modify it any way you want to suit your needs. I would really appreciate it if you would mention my name in the credits, but even there you do not have to feel obliged to do so.
To register components on clients' computers you'll have to write an installation program, or use the VB Package & Deployment wizard. This wizard, and other applications that help you create setup programs, such as "Wise InstallBuilder" or "InstallShield" allow you to specify all the components you'll need and they'll know which ones are self-registering (ActiveX) DLLs and EXEs and they'll register them for you as part of the installation process.

Typically, you'll need to modify:
AWXB01Thread.dll - Put in the code you want to run for each thread
AWXB03Test.exe - Replace this with your "main program".

You can also modify
AWXB02MSG.exe
if you want to be able to pass more complex information via the "message queue"
0
 
LVL 10

Expert Comment

by:caraf_g
ID: 2692553
"my name" <g>

Pino Carafa. See also homepage.eircom.net/~carafa
0
 
LVL 6

Author Comment

by:st_steve
ID: 2692957
caraf_g:...thanks a lot...I'm going to give you the points now...but "PLS CONTINUE TO MONITOR THIS QUESTION" in case I need more help?? :) thanks...

a few comments

for 1)..I wasn't really looking for a mathematical proof (like O(n) notation and stuff like that..)....but it's good that you have tested it out in real life...I actually tried a CPU-wasting loop..that's how I found out that my LU is blocking the application.

2) so all I need to do is creat a setup application and the activex will register themselves? that's great..coz right now..I'm using InstallShield Express 2.12

Please send me your details and other things that you may wish to disclose so that I can include the details in my project. I heard that we're not supposed to give out our email addresses here...so...???how do we contact each other??

0
 
LVL 6

Author Comment

by:st_steve
ID: 2692974
remember.....monitor this question...or gimme your email address..thanks .....
0
 
LVL 10

Expert Comment

by:caraf_g
ID: 2693323
Have you ever tried yahoo! messenger?
0
 
LVL 6

Author Comment

by:st_steve
ID: 2695335
yeah...my yahoo ID is: si_thu

hope to chat with ya some time...and HELP me..hehe...
0
 
LVL 6

Author Comment

by:st_steve
ID: 2695569
I've tried to change the two components (AWXB01Thread.dll & AWXB03Test.exe) I looked at 'AWXB01Thread.dll' and I found "Show" method. So is it that I create another 'method', probably named 'download' so that I can call it from AWXB03Test.exe, something like:

    Set objX = CreateObject("AWXB04Starter.AWXB04")
    objX.download

How about the stop button? how do I abort the download??

I dun want to use the AWXB02MSG.exe for message queue yet...I just want to get the basic threading working first.

My LU is actually on a form; coz I needed to use the "inet" control to 'HTTP' to the web server. So will that affect how the LU routine is called??

I've changed the reference names (like from 'AWXB04Starter' to something like 'ActiveXStarter')..they're working fine...after I had figured out that I had to add references to the projects. :) now..the only problem remaining is the integration of my LU form with your application...HELP????
0
 
LVL 10

Expert Comment

by:caraf_g
ID: 2696896
Hi Steve,

sorry for the slow response. I'm reformatting my PC and have just managed to reconnect now...

Anyway, glad to hear you're on yahoo! My ID is "rozeboosje"
Tomorrow I'll still be messing around with this PC but on Monday I should be able to give my undivided attention ;-)

Hope you can wait until then. Better get back to getting this PC up and running smoothly again.

Cheers

Pino
0
 
LVL 6

Author Comment

by:st_steve
ID: 2697493
Thanks Pino for all your help..and all the help to come :)....will catcha on yahoo.....
0
 

Expert Comment

by:txu
ID: 7499391
Hi, Guys:

The reason I post my question in this old post is there is nobody answer the question I posted two days ago and the question asked here is very similar to the question I have. Hope you guys could still see my questioin and help me out ...

I am trying to build a GUI with server socket runs in the background to listen any connection from clients and then send information back and forward between the foreground form and background sockets.

I think I need to run the background sockets in another thread. I tried CreateThread function from API and gave it up eventually because the application crashed sometimes with the reason I cann't tell. After some reasearch with the information I got from internet, I found some experts  talking aobout using createobject() function to create an object in a thread. then I tried to start from there.

I create an Active DLL which contain a class called serversock and then I create a function newsock() in this class. newsock is like follows

Public Function newsock() As Long

.....
socket()
bind()
listen()
accept()

end function

then I create another project for GUI and reference servercsock dll created above to this project. in the GUI project, I call the building  server socket in the form_load procedure since I want the server socket start to run as soons as the GUI is loaded

Private Sub Form_Load()
  Dim b As serversock
  Set b = CreateObject("Server.serversock")
  b.newsock()
End Sub

The GUI application hanged everytime the form is loaded because the accept() used in newsock().

I assume b is create in another thread when I call createobject() and so b.newsock(0 should run in the thread different from the thread where I run the GUI. It seems that I am wrong and they still run in the same thread, causing GUI to hang every time.

I really need your guys help out how to make the server sock run in another thread!!!!!!!! I am open for any suggestion !

million thanks,

Tom
0
 
LVL 10

Expert Comment

by:caraf_g
ID: 7502366
Hi Tom,

The reason why nobody is answering your question is probably because most VB experts have turned away from this site in disgust. A good few of them have gone .... er.... <cough>..... "elsewhere". Now I can't name that place here, but if you go a-lookin' for my name you can't miss it. And my name has already been mentioned in this thread. Good luck to ya!
0
 

Expert Comment

by:txu
ID: 7504319
Thanks, Pino!
0
 
LVL 10

Expert Comment

by:caraf_g
ID: 7504369
;-) See you at the other side of the fence
0
 
LVL 6

Author Comment

by:st_steve
ID: 7507199
Hi Pino

Glad to see you're still monitoring my question :)
0
 
LVL 10

Expert Comment

by:caraf_g
ID: 7507434
<g>

Ah well. Imagine if I had to go through all the threads I participated in in the year 2000 and unsubscribe from them all.....
0
 
LVL 6

Author Comment

by:st_steve
ID: 7507710
Ya, imagine that.
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

When designing a form there are several BorderStyles to choose from, all of which can be classified as either 'Fixed' or 'Sizable' and I'd guess that 'Fixed Single' or one of the other fixed types is the most popular choice. I assume it's the most p…
Since upgrading to Office 2013 or higher installing the Smart Indenter addin will fail. This article will explain how to install it so it will work regardless of the Office version installed.
Show developers how to use a criteria form to limit the data that appears on an Access report. It is a common requirement that users can specify the criteria for a report at runtime. The easiest way to accomplish this is using a criteria form that a…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

26 Experts available now in Live!

Get 1:1 Help Now