Threading !

Posted on 2006-04-11
Last Modified: 2008-02-01
What is the difference between "TerminateThread" and "ExitThread" APIs ?

I have created a new thread to process a lenghthy loop so VB doesn't hang and I can still get on with my other work during the loop.

I used the CreateThread API and it works as expected . What I  CAN'T  do is end the thread prematurely so I can exit the loop if it is far too long.

I have tried the 2 APIs above to kill the thread but it crashes the whole app ! (:

I have have already seen the example given on Site and searched the net for other more info but I can't find anything that works to end a thread !!!

Does anybody have a working example with "TerminateThread" or "ExitThread" APIs  to kill a thread ?


Question by:RAFAAJ
    LVL 29

    Expert Comment

    Curious to know if you tested when your application was compiled and not from the IDE. Your application should crash if you compiled in native code. If you compile in p-code you have a better chance that createthread would work.

    You can always get information from the remarks section of microsoft



    Author Comment

    Thanks egl,

    I am actually using VBA for this  not VB so no real compiler.

    I had already  seen those links but I am afraid, they are not very clear\helpful...and as usual no real working code examples are given to illustrate the concepts (:

    Any one has a concrete simple code that works ?

    LVL 29

    Accepted Solution

    One terminates the thread and the otherone will exit the thread, if your familiar with TerminateProcess and WM_CLOSE then you can think of it like that you never want to Terminate a process instead you want to close the process nicely by sending WM_CLOSE message. Any active threads that you want to exit for cleanup use exitthread if the thread doesn't close than you can call terminate thread but remember as microsoft says this is dangerouse depending on what operations are being performed in the thread which could lead to corruption. For example if you open the thread and withing the thread you don't want to proceed because something didn't meet a specific criteria then call exitthread if its a major operation exitthread might not work and then you will be have to force the termination of the thread which is where TerminateThread comes into play.

    Author Comment

    OK, let me be a bit more specific.

    Let's say that from within an Excel\VBA code, I want to seach the C drive for all files whose names include the letters "ab" and display the found files on a MsgBox.

    Obviously this is a good scenario for wanting to run the loop in a seperate thread so the use can still work with XL while the lenghthy code is searching the C drive and all its Folders.

    Using the CreateTread API all works fine for creating the new thread as well as running the lopp in its callback procedure. However if I wanted to abort the search , then I believe I would need to kill the Thread ...Right ?

    To do so I am trying the TerminateThread as shown in the code below .Unfortuantely, I can't it to work. Worse still, the App crashes !!!

    Code :

    'In a module
    Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
    Declare Function CreateThread Lib "kernel32" (lpThreadAttributes As Any, ByVal dwStackSize As Long, ByVal lpStartAddress As Long, lpParameter As Any, ByVal dwCreationFlags As Long, lpThreadID As Long) As Long
    Declare Function TerminateThread Lib "kernel32" (ByVal hThread As Long, ByVal dwExitCode As Long) As Long
    Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
    Public hThread As Long, hThreadID As Long

    Public blnRepeatSearch As Boolean

    Public Sub AsyncThread()

        Dim strFiles As String
        Dim i As Long
        With Application.FileSearch
            If blnRepeatSearch Then
            End If
            .LookIn = "C:"
            .SearchSubFolders = True
            .Filename = "ab"
            .MatchTextExactly = False
            .FileType = msoFileTypeAllFiles
            For i = 1 To .FoundFiles.Count
                strFiles = strFiles & vbCrLf & .FoundFiles(i)
            Next i
        End With
        MsgBox strFiles
        hThread = 0

    End Sub

    Sub StartThread()

        If blnRepeatSearch = False Then
            blnRepeatSearch = True
        End If
        hThread = CreateThread _
        (ByVal 0&, ByVal 0&, AddressOf AsyncThread, ByVal 0&, ByVal 0&, hThreadID)
        CloseHandle hThread

    End Sub

    Sub KillThread() ''''''''''''''''''NOT WORKING !!!!!

        If hThread <> 0 Then TerminateThread hThread, 0

    End Sub

    Any one knows how to make the code above work ??? ( ie: Make the killTread procedure work )


    LVL 29

    Expert Comment

    You would want to use exitthread inside the AsyncThread callback, you must also make sure to exit any type of active loops before calling exit thread

    Author Comment


    Any Idea how to apply that to the code ?

    Thanks .

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Free Trending Threat Insights Every Day

    Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

    Introduction In a recent article ( for the Excel community, I showed an improved version of the Excel Concatenate() function.  While writing that article I realized that no o…
    The debugging module of the VB 6 IDE can be accessed by way of the Debug menu item. That menu item can normally be found in the IDE's main menu line as shown in this picture.   There is also a companion Debug Toolbar that looks like the followin…
    As developers, we are not limited to the functions provided by the VBA language. In addition, we can call the functions that are part of the Windows operating system. These functions are part of the Windows API (Application Programming Interface). U…
    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…

    761 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

    11 Experts available now in Live!

    Get 1:1 Help Now