带返回值的多线程:vb.net

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25911816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 18:14:04  来源:igfitidea点击:

Multi Threading with Return value : vb.net

vb.netmultithreading

提问by Darryl

I had created a list of threadsto achieve Multi Threadingthat all accepting a single function that returning value. Following is the code that i had tried:

我创建了一个列表threads来实现Multi Threading所有接受一个返回值的函数。以下是我尝试过的代码:

Creation of threads

线程的创建

  Dim txt as String
  For i As Integer = 0 To 15
      txt = ""
      txt = UCase(array.Item(i))
      Dim tempThread As Threading.Thread = New Threading.Thread(AddressOf threadRead)
      tempThread .Start(txt) ' start thread by passing value to it
      Threads.Add(tempThread ) 'Add thread to the list
      'Here i want to add the return value from the thread to RichTextbox
      'as follows
      RichTextBox1.Text = RichTextBox1.Text & vbNewLine & tempThread.ReturnValue
  Next

Function that is addressed by the thread

线程寻址的函数

  Public Function threadRead(ByVal txtInput As String) As String
       Dim stroutput As String = ""
       ' Some operations are performed here
       Return stroutput
  End Function

So the problem is that i can't access the returning value from the called function. can anyone suggest me some method to achieve this?

所以问题是我无法访问被调用函数的返回值。谁能建议我一些方法来实现这一目标?

Thanks in advance

提前致谢

回答by Darryl

In my opinion, the easiest way to do this is with a helper object called a BackgroundWorker. You can find the MSDN documentation here.

在我看来,最简单的方法是使用名为 a 的辅助对象BackgroundWorker。您可以在此处找到 MSDN 文档。

Here's an example of how to use it:

以下是如何使用它的示例:

Private Sub RunFifteenThreads()
   For i As Integer = 1 To 15
      Dim some_data As Integer = i
      Dim worker As New System.ComponentModel.BackgroundWorker
      AddHandler worker.DoWork, AddressOf RunOneThread
      AddHandler worker.RunWorkerCompleted, AddressOf HandleThreadCompletion
      worker.RunWorkerAsync(some_data)
   Next
End Sub

Private Sub RunOneThread(ByVal sender As System.Object, _
                         ByVal e As System.ComponentModel.DoWorkEventArgs)
   Dim stroutput As String = e.Argument.ToString
   ' Do whatever else the thread needs to do here...
   e.Result = stroutput
End Sub

Private Sub HandleThreadCompletion(ByVal sender As Object, _
                                   ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs)
   Dim return_value As String = e.Result.ToString
   RichTextBox1.Text = RichTextBox1.Text & vbNewLine & return_value
End Sub

Each worker object manages its own thread. Calling a worker's RunWorkerAsyncmethod creates a new thread and then raises a DoWorkevent. The function that handles the DoWorkevent is executed in the thread created by the worker. When that function completes, the worker raises a RunWorkerCompletedevent. The function that handles the RunWorkerCompletedevent is executed in the original thread, the one that called RunWorkerAsync.

每个工作对象管理自己的线程。调用工作者的RunWorkerAsync方法会创建一个新线程,然后引发一个DoWork事件。处理DoWork事件的函数在worker创建的线程中执行。当该函数完成时,worker 会引发一个RunWorkerCompleted事件。处理RunWorkerCompleted事件的函数在原始线程中执行,即调用RunWorkerAsync.

To pass data between threads, you use the EventArgs parameters (ein the example above) in your event handlers. You can pass a single argument to RunWorkerAsync, which is made available to the new thread via e.Argument. To send data the other direction, from the worker thread to the main thread, you set the value of e.Resultin the worker thread, which is then passed to function which handles thread completion, also as e.Result.

要在线程之间传递数据,您可以e在事件处理程序中使用 EventArgs 参数(在上面的示例中)。您可以将单个参数传递给RunWorkerAsync,该参数通过 提供给新线程e.Argument。要从另一个方向发送数据,从工作线程到主线程,您e.Result在工作线程中设置 的值,然后将其传递给处理线程完成的函数,也作为e.Result

You can also send data between threads while the worker thread is still executing, using ReportProgressand ProgressChanged(see MSDN documentation if you're interested).

您还可以在工作线程仍在执行时在线程之间发送数据,使用ReportProgressProgressChanged(如果您感兴趣,请参阅 MSDN 文档)。

回答by Paul Ishak

Heres an idea

这是一个想法

    Event ValueAcquired(sender As Object, e As ValueAcquiredEventArgs)
    Delegate Sub delValueAcquired(sender As Object, e As ValueAcquiredEventArgs)
    Sub AllocateThread()
        Dim thStart As New System.Threading.ParameterizedThreadStart(AddressOf threadEntry)
        Dim th As New Threading.Thread(thStart)
        th.Start()
    End Sub
    Sub threadEntry()
        threadRead("whatever this is")
    End Sub
    Sub notifyValueAcquired(sender As Object, e As ValueAcquiredEventArgs)
        If Me.InvokeRequired Then
            Me.Invoke(New delValueAcquired(AddressOf notifyValueAcquired), sender, e)
        Else
            RaiseEvent ValueAcquired(sender, e)
        End If
    End Sub
    Public Sub threadRead(ByVal txtInput As String)
        Dim stroutput As String = ""
        ' Some operations are performed here
        'raise your event
        notifyValueAcquired(Me, New ValueAcquiredEventArgs(stroutput))
    End Sub
    Sub me_valueAcquired(sender As Object, e As ValueAcquiredEventArgs) Handles Me.ValueAcquired
        'Use e.Value to access the retrun value of threadRead
    End Sub
    Public Class ValueAcquiredEventArgs
        Public Value As String
        Sub New(value As String)
            Me.Value = value
        End Sub
    End Class