简体   繁体   English

运行一个功能的多线程线程VB.net

[英]Multiple Threading Thread running one function VB.net

I am having a weird issue. 我有一个奇怪的问题。

My checkedlistbox has 3 items in it. 我的清单中有3个项目。 I check all of the items and click on my button. 我检查所有项目,然后单击我的按钮。 The button should create the equal number of threads (as the checked items number) and give the index of the checkeditems to a function. 该按钮应创建相同数量的线程(作为选中项目的编号),并将选中项目的索引赋予函数。 The function gives out the checkeditems in the console. 该功能在控制台中给出了检查项目。

Public Class Form1
    Private ThreadList As New List(Of Threading.Thread)

    Private Sub MeineFunktion(ByVal username As String)
        Threading.Thread.Sleep(2000)
        Console.WriteLine(username)
        'Debug.Print(username)
    End Sub

 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim indexChecked As Integer


        For Each indexChecked In CheckedListBox1.CheckedIndices



            Dim t As Threading.Thread = New Threading.Thread(Sub() MeineFunktion(indexChecked.ToString))
            ThreadList.Add(t)
            t.Start()


        Next

    End Sub
End Class

The issue is, the console always gives out 问题是,控制台总是发出

1, 1, 2 一二一

Instead of 代替

0, 1, 2 0、1、2

Why is the first item always ignored? 为什么总是忽略第一项?

What I tried so far 到目前为止我尝试过的

Changing the byval username as INTEGER, and doing sneding the value like this 将byval用户名更改为INTEGER,并像这样固定值

Dim t As Threading.Thread = New Threading.Thread(Sub() MeineFunktion(indexChecked))

And still encountered the same issue. 并且仍然遇到相同的问题。 Either it has something to do with my threadings, or with the function which does the console writeline (I tried debug print as well). 要么与我的线程有关,要么与控制台写线有关的功能(我也尝试过调试打印)。

I can't pinpoint what is causing the issue 我无法查明是什么原因造成的

Each thread needs some time to be created and start running. 每个线程需要一些时间才能创建并开始运行。 It seems you are changing username before the thread can use it. 似乎您正在更改用户名 ,线程才能使用它。 Try to add a small delay just after each thread start: 尝试在每个线程启动之后添加一个小的延迟:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim indexChecked As Integer
    For Each indexChecked In CheckedListBox1.CheckedIndices
        Dim t As Threading.Thread = New Threading.Thread(Sub() MeineFunktion(indexChecked.ToString))
        ThreadList.Add(t)
        t.Start()
        Do
            Threading.Thread.Sleep(10)
        Loop Until t.IsAlive
    Next
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM