System Hangs While Copying a Folder

It is the following, I have a desktop application that copies a folder with several files from one location to another, however, when the files are being copied the application hangs, it appears that the system is not responding, and only unlock after the transfer of the files is completed. data. I also have a ProgressBar that would be to show the progress of the download, but as the application hangs it starts to populate the ProgressBar and once it unlocks it is already all populated. How can I make sure that the system does not lock during transfer and progressbar also works correctly. Use the template available in the documentation.
(Google translator)

Sub CopyFileOrFolder (source As FolderItem, destination As FolderItem)
  Dim newFolder As FolderItem
  
  If source.Directory Then // it's a folder
    newFolder = destination.Child (source.Name)
    newFolder.CreateAsFolder
    For i As Integer = 1 To source.Count // go through each item
      If source.Item (i) .Directory Then
        // it's a folder
        CopyFileOrFolder (source.Item (i), newFolder) // recursively call this routine passing it the folder
      Else
        source.Item (i) .CopyFileTo (newFolder) // it's a file so copy it
      End If
    Next
  Else // it's not a folder
    source.CopyFileTo (destination)
  End If
End Sub

If you wrap your code in the code tags it makes it easier to read

A loop like this will make the user interface behave as though its “stuck” simply because the loop does NOT release any time to the framework to do ANYTHING else
And that includes updating the progressbar

I understand. Sorry for not having code tags, I’m a beginner in Xojo and in the forum. But how can I solve this problem? For the system not to hang, does the loop stay in the background and the progressbar work? Thank you

[code]Sub CopyFileOrFolder (source As FolderItem, destination As FolderItem)
Dim newFolder As FolderItem

If source.Directory Then // it’s a folder
newFolder = destination.Child (source.Name )
newFolder.CreateAsFolder
For i As Integer = 1 To source.Count // go through each item
If source.Item (i) .Directory Then
// it’s a folder
CopyFileOrFolder (source.Item (i), newFolder) // recursively call this routine passing it the folder
Else
source.Item (i) .CopyFileTo (newFolder) // it’s a file so copy it
End If
Next
Else // it’s not a folder
source.CopyFileTo (destination)
End If
End Sub
[/code]

Have a look at the example UIThreadingWithTask.xojo_binary_project that comes with Xojo. The code is a bit complicated but it’s not too hard to use.