How to Start Multiple Threads Dynamically by casting variable names as Object

£可爱£侵袭症+ 提交于 2019-12-07 18:40:08

问题


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

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

and then start them

for i as integer = 0 to 5
    variableName & i.tostring" = New Thread(New ParameterizedThreadStart(AddressOf SubOrFunction))"
    variableName & i.tostring".Start(s)
  1. How would one accomplish this
  2. What is this actually called ( terminology )

Thanks in advance.


回答1:


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



回答2:


Create a Dictonary(of String, Thread) so can you easily access them

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

Start 'em

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

Or Start specific thread: dictThread("Thread3").Start(s)

Note: Just written, not tested ;)



来源:https://stackoverflow.com/questions/18533135/how-to-start-multiple-threads-dynamically-by-casting-variable-names-as-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!