2

不确定这会有多难,或者是否涉及铸造,但这是我想要的(请使用 vb.net 代码)

我想要的只是一个LoopThreads用不同的名字创造不同的东西。

dim variableName="Thread"
for i as Integer = 0 to 5
    "dim " & variableName & (i) & "as new Threading.Thread"
next

然后启动它们

for i as integer = 0 to 5
    variableName & i.tostring" = New Thread(New ParameterizedThreadStart(AddressOf SubOrFunction))"
    variableName & i.tostring".Start(s)
  1. 如何做到这一点
  2. 这实际上叫什么(术语)

提前致谢。

4

2 回答 2

2

通常,当您想为对象动态分配名称时,最好使用字典。在字典中,您将使用动态分配名称的键,并将值用作分配该名称的对象。例如:

Dim d As New Dictionary(Of String, MyClass)()

'Add objects to dictionary
d("dynamic name 1") = New MyClass()
d("dynamic name 2") = New MyClass()

'Get object from dictionary by name
Dim myObject As MyClass = d("dynamic name 1")

同样的方法也适用于线程,例如:

Dim threads As New Dictionary(Of String, Thread)()
Dim variableName = "Thread"
For i As Integer = 0 To 5
    threads(variableName & "(" & i.ToString() & ")") = New Thread()
Next

但是,如果您所做的只是为它们分配数字索引,而不是字符串名称,则可以只使用列表,如下所示:

Dim threads As New List(Of Thread)()
For i As Integer = 0 To 5
    threads.Add(New Thread())
Next

然后你可以通过索引从列表中获取线程,如下所示:

Dim t As Thread = threads(1)

或者,如果你有一定数量的线程,你可以很容易地使用一个数组:

Dim threads(4) As Thread
For i As Integer = 0 To 5
    threads(i) = New Thread()
Next
于 2013-08-30T12:52:47.240 回答
1

创建一个Dictonary(of String, Thread)这样您就可以轻松访问它们

Dim dictThread as new Dictionary(of String, Thread)
For i as integer = 0 to 5
   dictThread.add("Thread" & i.toString, New Thread(New ParameterizedThreadStart(AddressOf SubOrFunction))
Next

开始他们

For Each t as Thread in dictThread.Values
   t.Start(WhateverSIs)
Next

或启动特定线程:dictThread("Thread3").Start(s)

注意:只是写的,没有测试;)

于 2013-08-30T12:56:46.523 回答