VB and VBA Users Source Code: Creating new threads to perform asynchronous tasks
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
VB/VBA Source Code
Creating new threads to perform asynchronous tasks
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Monday, March 05, 2001
Hits:
3296
Category:
Windows API
Article:
The following demonstrates how to create new threads in Visual Basic. This can be an extremely useful techique for performing asynchronous tasks. Option Explicit 'MODULE CODE Public Const CTF_COINIT = &H8, CTF_INSIST = &H1 Public Const CTF_PROCESS_REF = &H4, CTF_THREAD_REF = &H2 Private Declare Function SHCreateThread Lib "shlwapi.dll" (ByVal lptrRoutine As Long, pData As Any, ByVal dwFlags As Long, ByVal pfnCallback As Long) As Long 'Purpose : Calls a function or sub in a new thread 'Inputs : lptrRoutine The address of the function/sub to call. Note, the function/sub must be declared in a standard module. ' [lFlag] One of the following: ' FLAG DESCRIPTION ' CTF_COINIT Initialize COM for the created thread before calling either the optional function pointed to by pfnCallback or the function pointed to by lptrRoutine. This flag is useful when COM needs to be initialized for a thread. COM will automatically be uninitialized as well. ' CTF_INSIST If the attempt to create the thread with CreateThread fails, setting this flag will cause the function pointed to by lptrRoutine to be called synchronously from the calling thread. This flag cannot be used if pfnCallback has a non-NULL value. ' CTF_PROCESS_REF Hold a reference to the Windows® Explorer process for the duration of the call to the function pointed to by lptrRoutine. This flag is useful for shell extension handlers, which might need to keep the Windows Explorer process from closing prematurely. Examples of where this action would be useful include tasks such as doing work on a background thread or copying files. For further information, see SHGetInstanceExplorer. ' CTF_THREAD_REF Hold a reference to the creating thread for the duration of the call to the function pointed to by lptrRoutine. This reference must have been set with SHSetThreadRef. 'Outputs : Returns True if the thread was successfully created. 'Author : Andrew Baker 'Date : 14/01/2001 12:20 'Notes : eg. To call this use: ' Call ThreadCreate (AddressOf myRoutineName) 'Revisions : Function ThreadCreate(lptrRoutine As Long, Optional lFlag As Long = CTF_INSIST) As Boolean On Error Resume Next ThreadCreate = CBool(SHCreateThread(lptrRoutine, ByVal 0&, CTF_INSIST, ByVal 0&)) On Error GoTo 0 End Function 'Demonstration routine: 'Create a modal msgbox in a separate thread Sub Test() ThreadCreate AddressOf NewThreadMsgbox Msgbox "This was created in this thread", vbInformation End Sub Sub NewThreadMsgbox() Msgbox "This was created in a new thread", vbInformation End Sub
Terms and Conditions
Support this site
Download a trial version of the Excel Workbook Rebuilder