Try using SyncLock
so the working thread locks the object and no other process access the file:
'Global variable lock
Dim objectLock As Object = New Object
Function Get_URL_SourceCode(ByVal url As String, Optional ByVal OutputFile As String = Nothing, Optional ByVal delimit As Boolean = False) As String
Dim SourceCode As String = String.Empty
'Lock object
SyncLock objectLock
If Want_to_cancel_thread Then Return Nothing
Try
Dim request As HttpWebRequest = HttpWebRequest.Create(url)
Dim response As HttpWebResponse = request.GetResponse()
Dim sr As StreamReader = New StreamReader(response.GetResponseStream())
SourceCode = sr.ReadToEnd()
sr.Close() : sr.Dispose()
If delimit Then SourceCode = Delimit_String(SourceCode, "<div id=""centercol"">", "<!--/centercol -->")
If OutputFile IsNot Nothing Then
'File.Open(OutputFile, FileMode.CreateNew, FileAccess.Write, FileShare.Write)
'Using TextFile As New StreamWriter(OutputFile, False, Encoding.Default)
' TextFile.WriteLine(SourceCode)
'End Using
File.WriteAllText(OutputFile, SourceCode, Encoding.Default)
End If
Catch ex As Exception
MsgBox("Error: " & ex.Message)
End Try
'End lock
End SyncLock
Return SourceCode
End Function