Some controls seem disposed when using delegates ... ?

G

Guest

Hi,

I'm using a delegate to edit some controls on formA from another thread on
formB.

This works nicely the first time I run formA. But if I close formA and
reopen it I get errors.

When changing the checked state of a radiobutton I get an error saying that
I cannot access the control since it is disposed. But I can still change the
text in a textbox without errors. The textboxes doesn't seem disposed to the
other thread, but the radiobuttons do.

Why this strange behaviour?
I'd be really thankfull for any help on this.

Best regards
Daniel

ps. below are the parts of my code that edit the controls. ds.


'these lines are in the other thread
Dim del As Measure.MyDelegate
del = New Measure.MyDelegate(AddressOf Measure.updateValues)
Dim xh As Object = Me.Handle
Me.BeginInvoke(del, currentValues) 'currentValues is an array of Objects

'in the declarations of Measure
Public Delegate Sub MyDelegate( ... ByVal value8 As Boolean, ByVal value9 As
String, ... )
Private Shared Event currentValuesChanged()
Private Shared rbnIn1Checked As Boolean = False
Private Shared txtSpeedText As String = ""

'in the OnLoad sub
AddHandler currentValuesChanged, AddressOf HandlerCurrentValuesChanged

'the sub that is executed using the delegate
Public Shared Sub updateValues( ... ByVal value8 As Boolean, ByVal value9 as
String, ... )
'...
rbnIn1Checked = value8
txtSpeedtext = value9
'...
RaiseEvent currentValuesChanged()
End Sub

'the handler of the event
Private Sub HandlerCurrentValuesChanged()
'...
Me.rbnIn1.Checked = rbnIn1Checked 'this line raises an error
Me.txtSpeed.text = txtSpeedtext 'this doesn't
'...
End Sub
 
C

Charles Law

Hi Daniel

I suspect that the problem is that you have an AddHandler call when you load
the form, but do not call RemoveHandler when the form closes. Therefore, the
HandlerCurrentValuesChanged function is trying to access controls on the old
form, which have been disposed.

HTH

Charles
 
G

Guest

Thank you Charles!

It seems that was it. It's working fine now.
I wasn't aware that I needed a RemoveHandler. Thank you very much for
teaching me that.

The very best of regards
/Daniel
 
M

Mattias Sjögren

I'm using a delegate to edit some controls on formA from another thread on
formB.

You should only manipulate controls from the UI thread they were
created on, not from background threads.



Mattias
 

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