如何通过将变量名强制转换为对象来动态启动多个线程 [英] How to Start Multiple Threads Dynamically by casting variable names as Object

查看:81
本文介绍了如何通过将变量名强制转换为对象来动态启动多个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不确定这将有多困难或是否涉及强制转换,但这是我想要的(请vb.net代码)

Not sure how hard this will be or if casting is involved but here is what i'd like ( vb.net code please )

我想要的是只是一个 Loop ,它将创建具有不同名称的不同 Threads

What I would like is simply a Loop that will create different Threads with different names.

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. 这实际上叫(术语)

先谢谢了。

推荐答案

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

Typically, when you want to assign names dynamically to objects, it's best to use a dictionary. In the dictionary, you would use the key for the dynamically assigned name and you would use the value as the object that is assigned that name. For instance:

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")

相同的方法也可以很好地用于线程,例如:

The same method will work well with threads, for instance:

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

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

However, if all you are doing is assigning numeric indexes to them, rather than string names, you could just use a list instead, like this:

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

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

Then you could get the thread from the list by index like this:

Dim t As Thread = threads(1)

或者,如果您有一定数量的线程,则可以轻松使用数组:

Or, if you have a set number of threads, you could easily use an array:

Dim threads(4) As Thread
For i As Integer = 0 To 5
    threads(i) = New Thread()
Next

这篇关于如何通过将变量名强制转换为对象来动态启动多个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆