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 use thread in for loop in c#

how to use thread in for loop in c#

Scheduled Pinned Locked Moved C#
csharpperformancetutorialquestion
26 Posts 7 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.
  • S superselector

    Hi i have a method which takes around 10sec to excute(sometimes more time) and store the data in datatable. i am calling this metod inside a for loop so the process is taking longer time. Please suggest a way to speed up the process. This method takes a input and generate a datarow and add that row to the global datatable. so there is same datatable which is being used throughout the for loop iterations. Please suggest how can i use thread in this case specially when we don't know how much time the method is going to take.

    S Offline
    S Offline
    Simon_Whale
    wrote on last edited by
    #9

    Question. Why are you calling a method that generates an individual row? Yhy not get all the data required at once and then populate the datatable?

    Every day, thousands of innocent plants are killed by vegetarians. Help end the violence EAT BACON

    S 1 Reply Last reply
    0
    • S superselector

      No i am creating a datarow.there is no database. i am creating the datatable using that row.

      public void GetData(DataTable dtAssetValues)
      {

      DataRow objdr = dtAssetValues.NewRow();
      try { objdr["OSName"] = GetValues(strKey);
      dtAssetValues.Rows.Add(objdr)
      }
      catch { }
      }

      here in this case the GetValues method has a Thread.Sleep(1000) of 1 sec. so there are 5-6 columns in the datatable for which i am calling this GetValues method to retrieve the column value. I am calling this GetData method inside a for loop. Hope this helps.

      L Offline
      L Offline
      Lost User
      wrote on last edited by
      #10

      Thread.Sleep is probably not the solution.

      S 1 Reply Last reply
      0
      • S Simon_Whale

        Question. Why are you calling a method that generates an individual row? Yhy not get all the data required at once and then populate the datatable?

        Every day, thousands of innocent plants are killed by vegetarians. Help end the violence EAT BACON

        S Offline
        S Offline
        superselector
        wrote on last edited by
        #11

        HI everyone, Thanks for you replies.I had never used thread before hence i had very little idea about multi-threding.I have removed the sleep inside the method as i found that it is not helping the cause.

        1 Reply Last reply
        0
        • L Lost User

          Thread.Sleep is probably not the solution.

          S Offline
          S Offline
          superselector
          wrote on last edited by
          #12

          the requirement goes like this ... I have set of ip's . i am looping through the IP list and for each ip i am checking whether i can ping them , i have given a time out of 4 seconds for ping reply. and am storing the result in a datatable.Pleas let me know how it can be implemented using threading to make the looping faster without losing any data as most of the ips are taking 3-4 seconds for reply.

          L 1 Reply Last reply
          0
          • S superselector

            the requirement goes like this ... I have set of ip's . i am looping through the IP list and for each ip i am checking whether i can ping them , i have given a time out of 4 seconds for ping reply. and am storing the result in a datatable.Pleas let me know how it can be implemented using threading to make the looping faster without losing any data as most of the ips are taking 3-4 seconds for reply.

            L Offline
            L Offline
            Lost User
            wrote on last edited by
            #13

            Ok, it's a little tricky. The simplest way, not very good is: make one thread for every ping action, start them all, then Join them all. Is that good enough for you? Otherwise, use ping.SendAsync, and make very sure that PingCompletedEventHandler is thread-safe. The handler will have to 1) save the result (safely! may involve locking) and 2) signal a waithandle (after saving the result). Then you can do a WaitAll over all the waithandles to continue when all the pings are done.

            S 1 Reply Last reply
            0
            • L Lost User

              Ok, it's a little tricky. The simplest way, not very good is: make one thread for every ping action, start them all, then Join them all. Is that good enough for you? Otherwise, use ping.SendAsync, and make very sure that PingCompletedEventHandler is thread-safe. The handler will have to 1) save the result (safely! may involve locking) and 2) signal a waithandle (after saving the result). Then you can do a WaitAll over all the waithandles to continue when all the pings are done.

              S Offline
              S Offline
              superselector
              wrote on last edited by
              #14

              if i follow the first option, Do in need to specify any timeout in Thread.Join method.

              L 1 Reply Last reply
              0
              • S superselector

                if i follow the first option, Do in need to specify any timeout in Thread.Join method.

                L Offline
                L Offline
                Lost User
                wrote on last edited by
                #15

                If the pings have a timeout, that should not be necessary, though it wouldn't be a problem either (as long as it's high enough to give the pings time to succeed).

                S 1 Reply Last reply
                0
                • L Lost User

                  If the pings have a timeout, that should not be necessary, though it wouldn't be a problem either (as long as it's high enough to give the pings time to succeed).

                  S Offline
                  S Offline
                  superselector
                  wrote on last edited by
                  #16

                  i think i need to specify timeout in join with more that 2500 ms as i have specified a time out of 2 sec. without any time out its very slow.

                  L 1 Reply Last reply
                  0
                  • S superselector

                    i think i need to specify timeout in join with more that 2500 ms as i have specified a time out of 2 sec. without any time out its very slow.

                    L Offline
                    L Offline
                    Lost User
                    wrote on last edited by
                    #17

                    But sometimes the pings took 4 seconds, right?

                    superselector wrote:

                    without any time out its very slow.

                    Well that's weird, it shouldn't take significantly longer than the longest running ping. Could you show the code?

                    S 1 Reply Last reply
                    0
                    • L Lost User

                      But sometimes the pings took 4 seconds, right?

                      superselector wrote:

                      without any time out its very slow.

                      Well that's weird, it shouldn't take significantly longer than the longest running ping. Could you show the code?

                      S Offline
                      S Offline
                      superselector
                      wrote on last edited by
                      #18

                      yes the time out takes 4 secs, i have given 2 secs for testing ... actually on successful ping checking for ping i am trying to get some basic details of that ip using WMI.WMI is taking some time also if its not enabled.

                      for (int index = startIP; index <= EndIP; index++)
                      {
                      ipVal = startSubnet + "." + index.ToString();

                                     Thread wmithread = new Thread(() => PerformWMIOperation(ipVal.ToString().Trim(), txtUserName.Text.ToString().Trim(), txtPassword.Text.ToString(), txtDomain.Text.ToString(), dtAssetValues, chkImpersonate.Checked, recordnumber));
                                      wmithread.Start();
                                      wmithread.Join(2500);
                                  }
                      
                      L 1 Reply Last reply
                      0
                      • S superselector

                        yes the time out takes 4 secs, i have given 2 secs for testing ... actually on successful ping checking for ping i am trying to get some basic details of that ip using WMI.WMI is taking some time also if its not enabled.

                        for (int index = startIP; index <= EndIP; index++)
                        {
                        ipVal = startSubnet + "." + index.ToString();

                                       Thread wmithread = new Thread(() => PerformWMIOperation(ipVal.ToString().Trim(), txtUserName.Text.ToString().Trim(), txtPassword.Text.ToString(), txtDomain.Text.ToString(), dtAssetValues, chkImpersonate.Checked, recordnumber));
                                        wmithread.Start();
                                        wmithread.Join(2500);
                                    }
                        
                        L Offline
                        L Offline
                        Lost User
                        wrote on last edited by
                        #19

                        Ok, not like that. Don't, "for every thread, start it, then join it". That just runs everything in serial. Do, "for every thread, start it. Then, for every thread, join it." That's how I said it: start them all then join them all.

                        S 1 Reply Last reply
                        0
                        • L Lost User

                          Ok, not like that. Don't, "for every thread, start it, then join it". That just runs everything in serial. Do, "for every thread, start it. Then, for every thread, join it." That's how I said it: start them all then join them all.

                          S Offline
                          S Offline
                          superselector
                          wrote on last edited by
                          #20

                          Hi i did not understand do you want the code to be changed to for (int index = startIP; index <= EndIP; index++) { ipVal = startSubnet + "." + index.ToString(); Thread wmithread = new Thread(() => PerformWMIOperation(ipVal.ToString().Trim(), txtUserName.Text.ToString().Trim(), txtPassword.Text.ToString(), txtDomain.Text.ToString(), dtAssetValues, chkImpersonate.Checked, recordnumber)); wmithread.Start(); wmithread.Join(); }

                          L 1 Reply Last reply
                          0
                          • S superselector

                            Hi i did not understand do you want the code to be changed to for (int index = startIP; index <= EndIP; index++) { ipVal = startSubnet + "." + index.ToString(); Thread wmithread = new Thread(() => PerformWMIOperation(ipVal.ToString().Trim(), txtUserName.Text.ToString().Trim(), txtPassword.Text.ToString(), txtDomain.Text.ToString(), dtAssetValues, chkImpersonate.Checked, recordnumber)); wmithread.Start(); wmithread.Join(); }

                            L Offline
                            L Offline
                            Lost User
                            wrote on last edited by
                            #21

                            That wouldn't help. The problem is this:

                            superselector wrote:

                            wmithread.Start(); wmithread.Join();

                            That's like calling that ping operation without a thread, except this way resources are wasted as well. Or to put it differently, it's like hiring a team to play a game of monopoly, in order to do it faster. That doesn't work. If everyone takes turns anyway, you might as well do it by yourself. You need an array of threads. Fill the array, start them all, then, and only then, join them all. Besides, what's with the WMI stuff? Do you need something that the Ping class[^] can't do?

                            S 1 Reply Last reply
                            0
                            • L Lost User

                              That wouldn't help. The problem is this:

                              superselector wrote:

                              wmithread.Start(); wmithread.Join();

                              That's like calling that ping operation without a thread, except this way resources are wasted as well. Or to put it differently, it's like hiring a team to play a game of monopoly, in order to do it faster. That doesn't work. If everyone takes turns anyway, you might as well do it by yourself. You need an array of threads. Fill the array, start them all, then, and only then, join them all. Besides, what's with the WMI stuff? Do you need something that the Ping class[^] can't do?

                              S Offline
                              S Offline
                              superselector
                              wrote on last edited by
                              #22

                              can you please give a sample code to implement this

                              L 1 Reply Last reply
                              0
                              • S superselector

                                can you please give a sample code to implement this

                                L Offline
                                L Offline
                                Lost User
                                wrote on last edited by
                                #23

                                Ok.. it's not that hard though.

                                Thread[] threads = new Thread[something];
                                for (int i = 0; i < threads.Length; i++)
                                {
                                threads[i] = new Thread(something);
                                threads[i].Start();
                                }
                                for (int i = 0; i < threads.Length; i++)
                                threads[i].Join();

                                S 2 Replies Last reply
                                0
                                • L Lost User

                                  Ok.. it's not that hard though.

                                  Thread[] threads = new Thread[something];
                                  for (int i = 0; i < threads.Length; i++)
                                  {
                                  threads[i] = new Thread(something);
                                  threads[i].Start();
                                  }
                                  for (int i = 0; i < threads.Length; i++)
                                  threads[i].Join();

                                  S Offline
                                  S Offline
                                  superselector
                                  wrote on last edited by
                                  #24

                                  hi with this approach , I am missing data .. means i am not getting output for all the IPs

                                  1 Reply Last reply
                                  0
                                  • L Lost User

                                    Ok.. it's not that hard though.

                                    Thread[] threads = new Thread[something];
                                    for (int i = 0; i < threads.Length; i++)
                                    {
                                    threads[i] = new Thread(something);
                                    threads[i].Start();
                                    }
                                    for (int i = 0; i < threads.Length; i++)
                                    threads[i].Join();

                                    S Offline
                                    S Offline
                                    superselector
                                    wrote on last edited by
                                    #25

                                    The ip address is getting overlapped. Means two rows are having same ip address.

                                    L 1 Reply Last reply
                                    0
                                    • S superselector

                                      The ip address is getting overlapped. Means two rows are having same ip address.

                                      L Offline
                                      L Offline
                                      Lost User
                                      wrote on last edited by
                                      #26

                                      Did you forget to use synchronization when saving the result?

                                      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