Link to home
Start Free TrialLog in
Avatar of chadmanvb
chadmanvb

asked on

background worker passing text to label and listview on main form .net visual basic

I would like to move a process to a background worker.  I need it to pass 2 varibles to the background worker, have it run a process, then return back 2 variables.  How can I do that?

dim str1 ="test1"
dim str2=test3"

BackgroundWorker1.RunWorkerAsync()  'need to pass str1 and str2 to this

Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
       

    End Sub 'return updated str1 and str2
ASKER CERTIFIED SOLUTION
Avatar of John (Yiannis) Toutountzoglou
John (Yiannis) Toutountzoglou
Flag of Greece image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
just for your label text change:
Private Sub SetVariable(ByVal StrVar As String)
        MyLabel.text = StrVar
    End Sub

Open in new window

Both good answers.  Sometimes I mix the two approaches together.

As demonstrated in Eric's article, you can pass in a parameter to the RunWorkerAsync() method.  If you have multiple values, then you can use a List(Of String), a simple array, or create a custom class to hold the values.  The important part here, though, is to cast "e.Argument" in the DoWork() handler back to whatever type you passed in so you can access the values within.

Similarly, you pass things OUT of the DoWork() handler by setting "e.Result" to something.  Again, you can pass out whatever type you want if you need to pass multiple items.  Just cast "e.Result" back to the correct type in the RunWorkerCompleted() event.

*The same thing can be done with ReportProgress() and the ProgressChanged() event.  There is an overload of ReportProgress() that accepts two parameters, with the second parameter being used to pass out information other than a simple integer for progress.  The "e.UserState" parameter in the ProgressChanged() event is then cast back to the correct type so you can access the values within.
>BackgroundWorker1.RunWorkerAsync()  'need to pass str1 and str2 to this
>End Sub 'return updated str1 and str2

Approaches described above are proper approaches but given that these are variables not controls on UI thread and you need to set them BEFORE calling worker and read them AFTER worker has completed, you can simply declare these as class level variables. Set these before calling the worker and read them back after worker has completed.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial