GeekZilla
Updating form controls from another thread.
Form controls, by default, can only be updated by the forms thread. Otherwise an invoke must be used.
The example below shows a simple logging function that can be called by threads other than the forms.
delegate void LogSafeCall(string s);
private void Log(string s) { if (EventsListBox.InvokeRequired) { LogSafeCall d = new LogSafeCall(Log); EventsListBox.Invoke(d, new object[] { s }); } else { EventsListBox.Items.Add(s); EventsListBox.SelectedIndex = EventsListBox.Items.Count - 1; } }
I have been involved in IT development for the last 10 years - a lot of it around desktop applications and telecoms.
Comments
enrique.prados@a-e.es
said:
Mister, my code is similar like this:
In DoWork event , I create controls child, and in ProgressChanged event I try add controls to SplitterPanel, but the application not responds. I use InvokeRequired for controls child.
Any suggestions, please ?
Private Sub bgCargaFichero_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgCargaFichero.DoWork
Try
'SplitContainer1.Panel1.SuspendLayout()
'SplitContainer1.Refresh()
' Procesar fichero
Me.ProcesarFicheroCargadoWork() ' IN THIS METHOD I CREATE CONTROLS Type = ContenedorVisorBase
'SplitContainer1.Panel1.ResumeLayout(False)
If bgCargaFichero.CancellationPending = True Then
e.Cancel = True
Else
e.Result = True
End If
End Sub
Private Sub bgCargaFichero_ProgressChanged(ByVal sender As System.Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bgCargaFichero.ProgressChanged
Dim contenedorPagina As GRUPOBACKUP.Administrador.Util.Cliente.ControlesWindows.ContenedorVisorBase = Nothing
contenedorPagina = CType(e.UserState, GRUPOBACKUP.Administrador.Util.Cliente.ControlesWindows.ContenedorVisorBase)
If contenedorPagina IsNot Nothing Then
AddMiniaturaToPanel(contenedorPagina)
End If
=====
Delegate Sub AddMiniaturaToPanelDelegate2(ByVal cCTL As Control)
Private Sub AddMiniaturaToPanel(ByVal cCTL As Control)
If cCTL.InvokeRequired Then
Dim d As New AddMiniaturaToPanelDelegate2(AddressOf AddMiniaturaToPanel)
Me.Invoke(d, New Object() {cCTL})
Else
SplitContainer1.Panel1.Controls.Add(cCTL) ' Here, the application not responds !!!!
End If
End Sub