我正在使用VB.Net 2010.我有一个函数,它检查数据库中的请求,并且一些请求可能需要几分钟才能完成。我不希望它在处理请求时排队,所以我想动态创建新线程来运行每个新请求,以便它们可以同时运行。我不确定我是否应该使用线程,线程池,后台工作者或其他东西。任何建议和示例代码都会很棒。我可以用一个简单的例子来工作。这是我迄今为止所有的。需要帮助在VB.Net中动态创建线程
谢谢。
Imports System.Threading
Module Module1
Private trd As Thread
Sub Main()
'START THREAD
trd = New Thread(AddressOf command_loop)
trd.IsBackground = True
trd.Start()
Console.ReadLine()
End Sub
Function command_loop()
'CREATE EXPORT FILE
Try
Dim f As FileInfo
Dim export As System.IO.StreamWriter
Dim arr_comment
'DELETE OLD EXPORT FILE
If File.Exists(export_path) Then
File.Delete(export_path)
End If
'VERIFY OLD EXPORT FILE WAS DELETED
If File.Exists(export_path) Then
writeToLog("ERROR: Old export file for " & username & " was not able to be deleted")
End If
'GET USER FOLDER CRC
Dim di As New DirectoryInfo(user_folder)
Dim fiArr As FileInfo() = di.GetFiles()
export = My.Computer.FileSystem.OpenTextFileWriter(export_path, True)
export.WriteLine("filepath, size, esize, date_mod_timestamp, timestamp, remote_filename, filestatus")
For Each f In fiArr
Try
Using zip As ZipFile = ZipFile.Read(user_folder & "\" & f.Name)
For Each e As ZipEntry In zip
If (zip.Comment IsNot Nothing) AndAlso (zip.Comment <> "") Then
arr_comment = Split(zip.Comment, ":")
End If
If arr_comment.length <> 3 Then
'FILE HAS AN INVALID COMMENT, SO DELETE IT.
zip.Dispose()
Try
writeToLog("Invalid zip file comment, deleting file " & user_folder & "\" & f.Name)
File.Delete(user_folder & "\" & f.Name)
writeToLog("Zip file successfully deleted")
Catch exx As Exception
writeToLog("Unable to delete invalid zip file")
writeToLog(exx.Message)
End Try
Continue For
End If
'CORRECT FILE PATH
Dim filepath = Replace(e.FileName, "/", "\\")
export.WriteLine(Chr(34) & filepath & Chr(34) & "," & e.UncompressedSize & "," & e.CompressedSize & "," & arr_comment(1) & "," & arr_comment(2) & "," & f.Name & "," & arr_comment(0))
Exit For
Next
End Using
Catch ex As IOException
Console.WriteLine(ex.Message)
Catch ex As ZipException
Console.WriteLine(ex.Message)
Try
writeToLog("Invalid zip file, deleting file " & user_folder & "\" & f.Name)
File.Delete(user_folder & "\" & f.Name)
writeToLog("Zip file successfully delete")
Catch e As Exception
writeToLog("Unable to delete invalid zip file")
writeToLog(e.Message)
End Try
End Try
Next f
export.Close()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Function
End Module
这个问题太广泛了。你需要缩小你正在做的事情并提出具体的问题。例如,“DO SOMETHING”方法中的代码可以极大地影响正确的解决方案。 – Enigmativity
你应该使用上面的所有那些+'Task.Run'。但它的确取决于最终目标 –
以下是需要加载到线程中的代码。 – rerat