Visual Basic Codes
ActiveX
Miscellaneous
Applications
Code Snippets
Common Dialogs
Special Effects
Database Stuff
Date Time
Files Drives
Forms
Graphics Games
Internet Stuff
Multimedia
Other
Strings
Windows
Visual Basic > Other sample source codes
Creating new threads to perform asynchronous tasks
Creating new threads to perform asynchronous tasks 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. '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
Privacy Policy
|
Link to Us
|
Links