在 VB.NET 中使用 3 个线程的多线程读取行



我尝试读取文件示例输出应该是字符串1字符串2字符串3

例如,我使用 3 个线程,我想读取 1 个文件,这是我启动线程的代码

For i = 0 To 3 - 1
 Dim HTTPFlood As New Threading.Thread(AddressOf TEST)
 HTTPFlood.Start()
 LIST.Add(HTTPFlood)
Next

这就是 IM 用来显示输出 im 的,首先尝试将文件拆分为 3 个 pease,然后尝试使其每个线程收集另一个文件以使其正确显示,但它给了我类似的东西

字符串1字符串1字符串2

public sub TEST
thread_connect += 1
thread_file = "C:UsersmsfdeDesktopb_" + thread_connect + ".txt"
For Each element As String In File.ReadAllLines(thread_file)
console.writeline(element)
next

谁能帮我阅读文件好,比如

字符串1字符串2字符串3

而不是

字符串1字符串1字符串1

我希望有人能帮我坐在这里 48 小时我尽了一切努力让每个线程读取另一行,但它太难了

首先,使用线程读取文件不会加快速度,因为您受到硬件的限制。其次,我不知道thread_connect是如何创建的,但它看起来并不安全。这意味着,2 个线程可能会增加thread_connect,创建thread_file然后两者都将使用相同的thread_file作为内部具有相同值的变量。您需要使其线程安全。

Public threadConnect As Integer = 0
Public lockObject As New Object
public sub TEST
    Dim filename As String ' Local variable, threads won't share the same variable 
    SyncLock lockObject ' Lock the thread to make sure they don't access the shared threadConnect variable at the same time
        threadConnect += 1
        filename = "C:UsersmsfdeDesktopb_" + threadConnect + ".txt"
    End SyncLock
    For Each element As String In File.ReadAllLines(filename)
        console.writeline(element)
    next

最新更新