Referring to form objects from inside a thread pool

J

Jerry Spence1

One way of passing data to a thread is to encapsulate the thread inside a
class. However, I can't refer to my main form objects from within the
class/thread as it says "Reference to a non-shared member requires an Object
reference".

How do I refer to items such as Textbox1.text etc on my main form?

-Jerry
 
F

Fred Hedges

Don't quote me, but I don't think it's good practice to refer to specific
components on a form from a thread. It couples the thread class and the
form too closely together. The best way I've found to do this is to store a
reference to an instance of the form in the thread class and then whenever
you want to signal to the main form to do something, "Invoke" a delegate on
the form. As an example of what this might look like below. We are
basically marshalling a call from the calling thread onto the form thread to
execute some function, passing in parameters. This function can contain
code to make modifications to your forms and/or the controls on them. I
usually have delegates for signalling error conditions, success, failure,
starting and ending an operation, but it all depends on what you are doing
with it.

http://msdn2.microsoft.com/en-us/library/zyzhdc6b.aspx





' Declare one or more delegates

Private Delegate Sub DoSomething_Delegate(...)

' Store a reference to an instance of the form you want to signal

Private m_Form as MainForm
......
......

' At some moment in the thread, invoke to the form.

Invoke_DoSomething (...)
.....
.....


' Invoke to the form, passing parameters (if required), via. a delegate.

Public Sub Invoke_DoSomething (...)

Dim Parameters(...) As Object

Parameters(0) = ...
Parameters(1) = ...
Parameters(2) = ...
Parameters(3) = ...

....

Try

m_Form.Invoke(New DoSomething_Delegate(AddressOf
m_Form.DoSomething_Invoked), Parameters)

Catch ex As Exception

' Something went titsup.

End Try

End Sub



' Create a method on the form called "DoSomething_Invoked"

Public Sub DoSomething_Invoked(....)

....
....Modify controls etc.
....

End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top