Link to home
Start Free TrialLog in
Avatar of CodeJunky
CodeJunkyFlag for United States of America

asked on

Threading with a function returning value to windows form control

Hi all,
I'm trying to create a thread that passes parameters into a function. the return value needs to be set to a label control.  I'm having a problem figuring out how to do this.

the function looks like this:
lblFILESIZE.Text = CONVERT_FILESIZE(GET_FILESIZE(txtSOURCE.Text, COPY_TYPE$), False)

any help would be greatly appreciated.
thanks,
John.
ASKER CERTIFIED SOLUTION
Avatar of Luis Pérez
Luis Pérez
Flag of Spain 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
Avatar of CodeJunky

ASKER

could you provide an example?
Imports System.Threading

'At form level:
Private _myThread As Thread = Nothing
Private _myVariable As String = String.Empty

'When you want to start your thread
_myThread = New Thread(AddressOf MiThreadSub)
_myThread.Start()
'Monitorize thread
While _myThread.IsAlive()
    Application.DoEvents() 'Or, better, check for your thread alive status into a timer
End While
'Once outside of the while...end while, your thread has finished
'Now you can check your _myVariable status and put it into a label or wherever you want
Me.Label1.Text = _myVariable

'What your thread does:
Private Sub MiThreadSub()
    '... do something
    'If the thread is executing inside a Windows Form, you cannot access Form objects
    'such as labels, etc.
    'But you can store values into form variables
    'For example:
    _myVariable = "Hello"
End Sub

Open in new window


Note that this code doesn't work if you simply paste it into a Form. For example, the "When you want to start your thread" block needs to be written somewhere it can execute, for example, a button's click event.

Hope that helps.
I figured it out.
I created a backgroundworker object
I created a variable to hold the result from the function within the backgroundworker .DoWork procedure.
I created a backgroundworker .RunWorkerCompleted procedure where I set that variable to the object it is meant for.

thanks,
John.