• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 229
  • Last Modified:

Accessing form main controls from a created thread.

I have a function that updates a progressbar in a loop. I want to create a thread for a progress bar update. How can I get formMain in the ThreadTask() function? Im unsure how to call this function and access the form controls.

Main function:
Imports System.Threading

Private trd As Thread

Public Sub Main(ByVal myExcelDataset As DataSet, ByRef frm As frmMain)
     formMain = frmMain

     'reset progress bar
     formMain.ProgBar.Value = 0
     For i As Integer = 0 To myExcelDataset.Tables("ExcelDoc").Rows.Count - 1
          'need to update the progressbar thread here!
     Next i
     formMain.lbStatus.Items(1) = "Inserting Projects... 100%"
     formMain.lbStatus.Items(1) = "Inserting Projects... Complete!"
End Sub

Private Sub ThreadTask()
      frm.lbStatus.Items(1) = "Copying to database..." & Int(formMain.ProgBar.Value * 100 / formMain.ProgBar.Maximum) & "%"
      frm.ProgBar.Value = formMain.ProgBar.Value + 1
End Sub
1 Solution
I see that your ThreadTask method is not shared (or "static" like in C#). You can access your class fields from that method, but control's are not thread safe and control member's can't be accessed (this is possible, but problems can occur) from thread another than thread where that control's was created.

You must marshal code which access members of control's to thread in which that control's was created using Invoke or BeginInvoke of Control class, actually that must be instance of your form.
C# code:
private class ProgressState {
   public string state;
private void MethodWhichAccessUnsafeControlMembers(Object stateObj) {
  ProgressState state = (ProgressState)stateObj;
  form.lblStatus.Text = state.state;
private void ThreadTask() {
  ProgressState state = new ProgressState();
  state.state = "Copying to database...";
  // let's check is control created (has windows handle) and
  // member's can be accessed
  if ( form.InvokeRequered ) {
    form.Invoke(new ParameterizedThreadStart
       (MethodWhichAccessUnsafeControlMembers), state);
  } else {
    MethodWhichAccessUnsafeControlMembers( state );

Open in new window


Featured Post

The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now