Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
CODE PROJECT For Those Who Code
  • Home
  • Articles
  • FAQ
Community
  1. Home
  2. General Programming
  3. C#
  4. How to access multiple controls thread safe in Windows Forms

How to access multiple controls thread safe in Windows Forms

Scheduled Pinned Locked Moved C#
winformstutorialquestionannouncement
10 Posts 4 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • P Offline
    P Offline
    poda
    wrote on last edited by
    #1

    Many examples explains thread safe access over a single control,like updating a text of a button or label etc.,How to change properties of multiple controls of a Form in thread safe manner.

    private Thread CheckStatusThread = null;
    public delegate void CheckStatusDelegate(int Count);
    public CheckStatusDelegate CheckStatusHandler;

    public Form1()
    {
    InitializeComponent();
    CheckStatusThread = new Thread(new ThreadStart(CheckStatusThreadFunc));
    CheckStatusHandler = new CheckStatusDelegate(CheckPowerStatus);
    }
    private void Form1_Load(object sender, EventArgs e)
    {
    CheckStatusThread.Start();
    }
    public void CheckStatusThreadFunc()
    {
    int Cnt = 1;
    while (true)
    {
    this.Invoke(CheckStatusHandler,new object []{Cnt});//executed in Form1's own thread(?)
    Cnt++;
    Thread.Sleep(500);
    }
    }

    public void CheckPowerStatus(int Count)
    {
    int Cnt=Count;

    //Update 3 controls properties
    StatusBarLabel1.Text = "Checking PowerStatus " + Cnt;
    dataGridView1.Rows[2].Cells[4].Value = Cnt;
    label1.Text = Convert.ToString("Cnt "+Cnt);
    }

    The CheckPowerStatus function change properties of 3 controls in Form1. Do I need to use 3 delegates to update each control on 3 different functions. Or the above code is thread safe?

    M L 2 Replies Last reply
    0
    • P poda

      Many examples explains thread safe access over a single control,like updating a text of a button or label etc.,How to change properties of multiple controls of a Form in thread safe manner.

      private Thread CheckStatusThread = null;
      public delegate void CheckStatusDelegate(int Count);
      public CheckStatusDelegate CheckStatusHandler;

      public Form1()
      {
      InitializeComponent();
      CheckStatusThread = new Thread(new ThreadStart(CheckStatusThreadFunc));
      CheckStatusHandler = new CheckStatusDelegate(CheckPowerStatus);
      }
      private void Form1_Load(object sender, EventArgs e)
      {
      CheckStatusThread.Start();
      }
      public void CheckStatusThreadFunc()
      {
      int Cnt = 1;
      while (true)
      {
      this.Invoke(CheckStatusHandler,new object []{Cnt});//executed in Form1's own thread(?)
      Cnt++;
      Thread.Sleep(500);
      }
      }

      public void CheckPowerStatus(int Count)
      {
      int Cnt=Count;

      //Update 3 controls properties
      StatusBarLabel1.Text = "Checking PowerStatus " + Cnt;
      dataGridView1.Rows[2].Cells[4].Value = Cnt;
      label1.Text = Convert.ToString("Cnt "+Cnt);
      }

      The CheckPowerStatus function change properties of 3 controls in Form1. Do I need to use 3 delegates to update each control on 3 different functions. Or the above code is thread safe?

      M Offline
      M Offline
      Mycroft Holmes
      wrote on last edited by
      #2

      All threading issues get referred to Luc - see his articles[^] here.

      Never underestimate the power of human stupidity RAH

      L 1 Reply Last reply
      0
      • P poda

        Many examples explains thread safe access over a single control,like updating a text of a button or label etc.,How to change properties of multiple controls of a Form in thread safe manner.

        private Thread CheckStatusThread = null;
        public delegate void CheckStatusDelegate(int Count);
        public CheckStatusDelegate CheckStatusHandler;

        public Form1()
        {
        InitializeComponent();
        CheckStatusThread = new Thread(new ThreadStart(CheckStatusThreadFunc));
        CheckStatusHandler = new CheckStatusDelegate(CheckPowerStatus);
        }
        private void Form1_Load(object sender, EventArgs e)
        {
        CheckStatusThread.Start();
        }
        public void CheckStatusThreadFunc()
        {
        int Cnt = 1;
        while (true)
        {
        this.Invoke(CheckStatusHandler,new object []{Cnt});//executed in Form1's own thread(?)
        Cnt++;
        Thread.Sleep(500);
        }
        }

        public void CheckPowerStatus(int Count)
        {
        int Cnt=Count;

        //Update 3 controls properties
        StatusBarLabel1.Text = "Checking PowerStatus " + Cnt;
        dataGridView1.Rows[2].Cells[4].Value = Cnt;
        label1.Text = Convert.ToString("Cnt "+Cnt);
        }

        The CheckPowerStatus function change properties of 3 controls in Form1. Do I need to use 3 delegates to update each control on 3 different functions. Or the above code is thread safe?

        L Offline
        L Offline
        Luc Pattyn
        wrote on last edited by
        #3

        you're not allowed to touch a Control from a random thread, so yes you need one or more Invoke calls. The proper way to handle simultaneous Control updates is by stuffing all the data you need in a little suitcase (i.e. a little class) and invoke once, let the delegate unpack the suitcase and do whatever needs to be done to the GUI. Assuming all GUI Controls got created on the main thread, all those Control.Invoke calls are equivalent anyhow, they all send the delegate to the main thread, no matter what they do to which Control. This[^] article of mine explains the basics, you may know most of it already. :)

        Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

        Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.

        P realJSOPR 2 Replies Last reply
        0
        • M Mycroft Holmes

          All threading issues get referred to Luc - see his articles[^] here.

          Never underestimate the power of human stupidity RAH

          L Offline
          L Offline
          Luc Pattyn
          wrote on last edited by
          #4

          Interesting link. :rose:

          Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

          Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.

          1 Reply Last reply
          0
          • L Luc Pattyn

            you're not allowed to touch a Control from a random thread, so yes you need one or more Invoke calls. The proper way to handle simultaneous Control updates is by stuffing all the data you need in a little suitcase (i.e. a little class) and invoke once, let the delegate unpack the suitcase and do whatever needs to be done to the GUI. Assuming all GUI Controls got created on the main thread, all those Control.Invoke calls are equivalent anyhow, they all send the delegate to the main thread, no matter what they do to which Control. This[^] article of mine explains the basics, you may know most of it already. :)

            Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

            Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.

            P Offline
            P Offline
            poda
            wrote on last edited by
            #5

            In article, you suggest to use Control and the property as generic parameter. But Control is the base class.The common property is only Text for all controls. But in case of specific properties of a control,how can use generic method. Suppose DataGridView.Rows[2].Cells[3].Value-how can use Control? Because Control.Rows does not exists. So if I need to update or access 3 controls 2 properties, then have to write 6 delegates and 6 functions to do the job?

            L 1 Reply Last reply
            0
            • P poda

              In article, you suggest to use Control and the property as generic parameter. But Control is the base class.The common property is only Text for all controls. But in case of specific properties of a control,how can use generic method. Suppose DataGridView.Rows[2].Cells[3].Value-how can use Control? Because Control.Rows does not exists. So if I need to update or access 3 controls 2 properties, then have to write 6 delegates and 6 functions to do the job?

              L Offline
              L Offline
              Luc Pattyn
              wrote on last edited by
              #6

              Actually I already answered that; here is one way:

              // the anonymous form (C# consumer)
              public void SetCount(int count) {
              dataGridView1.Invoke(new MethodInvoker(delegate() {
              StatusBarLabel1.Text = "Checking PowerStatus " + count;
              dataGridView1.Rows[2].Cells[4].Value = count;
              label1.Text = Convert.ToString("Cnt "+count);
              }));
              }

              :)

              Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

              Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.

              P 1 Reply Last reply
              0
              • L Luc Pattyn

                you're not allowed to touch a Control from a random thread, so yes you need one or more Invoke calls. The proper way to handle simultaneous Control updates is by stuffing all the data you need in a little suitcase (i.e. a little class) and invoke once, let the delegate unpack the suitcase and do whatever needs to be done to the GUI. Assuming all GUI Controls got created on the main thread, all those Control.Invoke calls are equivalent anyhow, they all send the delegate to the main thread, no matter what they do to which Control. This[^] article of mine explains the basics, you may know most of it already. :)

                Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

                Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.

                realJSOPR Offline
                realJSOPR Offline
                realJSOP
                wrote on last edited by
                #7

                Required reading, if you ask me. :)

                .45 ACP - because shooting twice is just silly
                -----
                "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                -----
                "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001

                P 1 Reply Last reply
                0
                • L Luc Pattyn

                  Actually I already answered that; here is one way:

                  // the anonymous form (C# consumer)
                  public void SetCount(int count) {
                  dataGridView1.Invoke(new MethodInvoker(delegate() {
                  StatusBarLabel1.Text = "Checking PowerStatus " + count;
                  dataGridView1.Rows[2].Cells[4].Value = count;
                  label1.Text = Convert.ToString("Cnt "+count);
                  }));
                  }

                  :)

                  Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

                  Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.

                  P Offline
                  P Offline
                  poda
                  wrote on last edited by
                  #8

                  Thanks for your replies Luc Pattyn. Here you only use dataGridView1.Invoke, but update other controls also.Is that ok?

                  L 1 Reply Last reply
                  0
                  • realJSOPR realJSOP

                    Required reading, if you ask me. :)

                    .45 ACP - because shooting twice is just silly
                    -----
                    "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                    -----
                    "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001

                    P Offline
                    P Offline
                    poda
                    wrote on last edited by
                    #9

                    Would you please kindly refer me some links.

                    1 Reply Last reply
                    0
                    • P poda

                      Thanks for your replies Luc Pattyn. Here you only use dataGridView1.Invoke, but update other controls also.Is that ok?

                      L Offline
                      L Offline
                      Luc Pattyn
                      wrote on last edited by
                      #10

                      poda wrote:

                      Is that ok?

                      Yes. I told you before: all those Control.Invoke calls are equivalent anyhow, they all send the delegate to the main thread, no matter what they do to which Control. And you're welcome. :)

                      Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

                      Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups