0

I am trying to learn threading and I have a few issues that I cannot work out:

Imagine I had this in my code:

Public Sub Compute(ByVal argument1 As String, ByVal argument2 As String)
       ' Code to be run that I'd like on a background worker thread
End Sub

And I wanted to turn it into something like this:

Private Sub btnCompute_Click(sender As Object, e As EventArgs) Handles btnCompute.Click
    BackGroundWorker1.RunWorkerAsync(argument1, argument2)
End Sub

Private Sub BackGroundWorker1_DoWork(sender As Object, e As ComponentModel.DoWorkEventArgs) Handles BackGroundWorker1.DoWork
    'Code to be run that I'd like on a background worker thread.
    'This section should be able to use argument1 and argument2.
End Sub

I'd like to know if this is the sort of thing I should be doing, and if not how/where I can improve the code to achieve my desired results, but I feel I'm a little out of my depth with this.

  • 1
    Refer to this answer: http://stackoverflow.com/questions/4807152/sending-arguments-to-background-worker – dcp Jan 11 '14 at 01:31

1 Answers1

1

Use a class object:

Public Class Foo
 Public foobar As String
 Public fubar As String
End Class

Dim _foo As New Foo
_foo.foobar = "great foo"
_foo.fubar = "wonderful foo"

worker.RunWorkerAsync(_foo)

Then cast it back inside the DoWork event.

Private Sub worker_DoWork(...) Handles ...
 Dim foo = DirectCast(e.Argument, Foo)
 'now you can use the properties you set on the Foo object.
End Sub
OneFineDay
  • 9,004
  • 3
  • 26
  • 37