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
  1. Home
  2. General Programming
  3. C#
  4. Thread instance object location

Thread instance object location

Scheduled Pinned Locked Moved C#
tutorialquestion
4 Posts 2 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 Offline
    S Offline
    Spacix One
    wrote on last edited by
    #1

    Is it wrong to use an instance property to hold the instance of a thread? Example code of what I mean:

    using System;
    using System.Threading;
    using System.Collections;
    using System.Windows.Forms;
    using System.IO;
    using newThreads;

    namespace newThreads
    {
    class newThread
    {
    private uint i;
    newThread()
    {
    i=0;
    }
    newThread(uint I)
    {
    i=I;
    }
    newThread(int I)
    {
    i=Convert.ToUInt32(I);
    }
    private volatile bool bExit = false;
    public void threadMethod()
    {
    /* do stuff before form loads ect... */
    while (!bExit)
    {
    ++i;
    Thread.Sleep(1500);
    }
    }
    public void ResetThread()
    {
    i = 0;
    public void ThreadExit()
    {
    bExit = false;
    }
    }
    }
    namespace newApp
    {
    public class winFormApp : System.Windows.Forms.Form
    {
    private newThreads _newThread;
    public newThreads newThread
    {
    get
    {
    return _newThread;
    }
    set
    {
    _newThread = value;
    }
    }

        public winFormApp()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();
            //
            // User constructor code after InitializeComponent call
            //
        }
    
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }
    
        #region Windows Form Designer generated code
        private void InitializeComponent()
        {
            /\* clip for size \*/
        }
        #endregion
    
        \[STAThread\]
        static void Main()
        {
            Application.EnableVisualStyles();
    
            using (winFormApp mainForm = new winFormApp())
            {
                mainForm.newThread = new newThreads.newThread();
    
                Thread newThreadID = new Thread(mainForm.newThread.threadMethod);
                newThreadID.Start();
    
                while (!newThreadID.IsAlive)
                {
    
    L 1 Reply Last reply
    0
    • S Spacix One

      Is it wrong to use an instance property to hold the instance of a thread? Example code of what I mean:

      using System;
      using System.Threading;
      using System.Collections;
      using System.Windows.Forms;
      using System.IO;
      using newThreads;

      namespace newThreads
      {
      class newThread
      {
      private uint i;
      newThread()
      {
      i=0;
      }
      newThread(uint I)
      {
      i=I;
      }
      newThread(int I)
      {
      i=Convert.ToUInt32(I);
      }
      private volatile bool bExit = false;
      public void threadMethod()
      {
      /* do stuff before form loads ect... */
      while (!bExit)
      {
      ++i;
      Thread.Sleep(1500);
      }
      }
      public void ResetThread()
      {
      i = 0;
      public void ThreadExit()
      {
      bExit = false;
      }
      }
      }
      namespace newApp
      {
      public class winFormApp : System.Windows.Forms.Form
      {
      private newThreads _newThread;
      public newThreads newThread
      {
      get
      {
      return _newThread;
      }
      set
      {
      _newThread = value;
      }
      }

          public winFormApp()
          {
              //
              // Required for Windows Form Designer support
              //
              InitializeComponent();
              //
              // User constructor code after InitializeComponent call
              //
          }
      
          protected override void Dispose(bool disposing)
          {
              if (disposing)
              {
                  if (components != null)
                  {
                      components.Dispose();
                  }
              }
              base.Dispose(disposing);
          }
      
          #region Windows Form Designer generated code
          private void InitializeComponent()
          {
              /\* clip for size \*/
          }
          #endregion
      
          \[STAThread\]
          static void Main()
          {
              Application.EnableVisualStyles();
      
              using (winFormApp mainForm = new winFormApp())
              {
                  mainForm.newThread = new newThreads.newThread();
      
                  Thread newThreadID = new Thread(mainForm.newThread.threadMethod);
                  newThreadID.Start();
      
                  while (!newThreadID.IsAlive)
                  {
      
      L Offline
      L Offline
      Luc Pattyn
      wrote on last edited by
      #2

      Hi, I have several comments on your code: 1. identifiers are case-sensitive, but having two variables differ in casing only is a bad idea, so I do not recommend your line i=I;. For one, you will confuse yourself, and furthermore if you read this aloud to someone, he won't understand you at all. Remark: nevertheless, people often have properties and local values that differ only by the casing of their first letter, so you could have public int Something {set {something=value;}} which is generally accepted and understood by everyone. 2. I don't like the newThread names (both namespace and class) very much. Everything is new at first, and gets old by itself, so I would avoid having new in such names. I would suggest "MyThread", "TestThread", "SomeSpecialThreadDoingSoAndSo", whatever best describes it. It may seem irrelevant, but picking appropriate names will help you as soon as you (or a team of people) get involved in bigger projects, so I recommend taking care of this from day one. 3. The line Thread.Sleep(1); will not behave exactly as you expect, it will typically sleep for 10 or more milliseconds; you may want to read my timers article. 4. To answer your specific question: the sequence - call constructor (mainForm = new winFormApp) - set some properties (mainForm.newThread =) - now call a method to start something happening (Application.Run(mainForm) is quite common, and in fact it is most often better than using a constructor or a method with a lot of parameters. However, I don't particularly like the idea of passing a thread to some class. If the class is about a thread experiment, I would put all the thread related code inside the class, it does not help having half of it in the class, and half outside. If the class needs a thread for its own purposes (making the thread irrelevant to the outside), I would definitely put all the thread stuff inside). 5. I didn't like the newThreadID = new Thread(...); line much, i.e. the variable's name should be newThread, not newThreadID, since it really is a thread (a threadID is a number identifying a thread at the kernel level, a Thread is an instance of the Thread class). 6. In general it is not a good idea to kill/abort a thread; it is a drastic measure to terminate it immediately, with the disadvantage that it potentially leaves its objects in an unknown state (files open, resources locked, whatever). So it should be avoided if possible. Here the intent seems to be t

      S 1 Reply Last reply
      0
      • L Luc Pattyn

        Hi, I have several comments on your code: 1. identifiers are case-sensitive, but having two variables differ in casing only is a bad idea, so I do not recommend your line i=I;. For one, you will confuse yourself, and furthermore if you read this aloud to someone, he won't understand you at all. Remark: nevertheless, people often have properties and local values that differ only by the casing of their first letter, so you could have public int Something {set {something=value;}} which is generally accepted and understood by everyone. 2. I don't like the newThread names (both namespace and class) very much. Everything is new at first, and gets old by itself, so I would avoid having new in such names. I would suggest "MyThread", "TestThread", "SomeSpecialThreadDoingSoAndSo", whatever best describes it. It may seem irrelevant, but picking appropriate names will help you as soon as you (or a team of people) get involved in bigger projects, so I recommend taking care of this from day one. 3. The line Thread.Sleep(1); will not behave exactly as you expect, it will typically sleep for 10 or more milliseconds; you may want to read my timers article. 4. To answer your specific question: the sequence - call constructor (mainForm = new winFormApp) - set some properties (mainForm.newThread =) - now call a method to start something happening (Application.Run(mainForm) is quite common, and in fact it is most often better than using a constructor or a method with a lot of parameters. However, I don't particularly like the idea of passing a thread to some class. If the class is about a thread experiment, I would put all the thread related code inside the class, it does not help having half of it in the class, and half outside. If the class needs a thread for its own purposes (making the thread irrelevant to the outside), I would definitely put all the thread stuff inside). 5. I didn't like the newThreadID = new Thread(...); line much, i.e. the variable's name should be newThread, not newThreadID, since it really is a thread (a threadID is a number identifying a thread at the kernel level, a Thread is an instance of the Thread class). 6. In general it is not a good idea to kill/abort a thread; it is a drastic measure to terminate it immediately, with the disadvantage that it potentially leaves its objects in an unknown state (files open, resources locked, whatever). So it should be avoided if possible. Here the intent seems to be t

        S Offline
        S Offline
        Spacix One
        wrote on last edited by
        #3

        Thanks for the comments and input. Responses: 1. & 2. Comments based off the simplified example code. Sorry if I wasted your time analizing the code rather than the "general" design. 3. timing doesn't matter, just a delay to prevent 100% CPU / thread lock if for some unknown reason the thread doesn't start right away. Which would be a case 1 out of 1000000 or more... I just need to know if it is active and running before I start up the form else trouble might start brewing 4. You seem to have come to the same conclusion I did but with minor differences   A. I'm not passing the thread to the form but storing it's class instance in a property, which is diffrent / unheard of to me.   B. I'm more worried about what happens if form get thrown to the GC before the thread finishes, because the class instance will stay with all data intact until the GC junks it. I've used setup properties before, which is why I thought of this. I do think this is better than running a method to get the device handles, save them to a public static ArrayList (yuck!), start the form, via onload event start processing the devices based off the public static ArrayList in a new timer thread, and then onclosing event to close the devices handles and wait for the last timer thread to die. 5. see 1. & 2. 6. Considering that the thread is holding handles to USB devices, I can't make it in the background. If the thread can't finish and exit within 3 seconds (~16-18 loops in the thread) after calling join() and setting the exit flag. Then it is soft locked and wouldn't matter if I killed it. Since the app is closing anyway it's ok to just junk it and the USB port handle will timeout at ~750ms via my driver. The problem here is it's better to allow the thread to finish for it might be witting to e2 on the device. Which is bad if you save to the the device and close the form before it is 100% written.


        -Spacix All your skynet questions[^] belong to solved

        L 1 Reply Last reply
        0
        • S Spacix One

          Thanks for the comments and input. Responses: 1. & 2. Comments based off the simplified example code. Sorry if I wasted your time analizing the code rather than the "general" design. 3. timing doesn't matter, just a delay to prevent 100% CPU / thread lock if for some unknown reason the thread doesn't start right away. Which would be a case 1 out of 1000000 or more... I just need to know if it is active and running before I start up the form else trouble might start brewing 4. You seem to have come to the same conclusion I did but with minor differences   A. I'm not passing the thread to the form but storing it's class instance in a property, which is diffrent / unheard of to me.   B. I'm more worried about what happens if form get thrown to the GC before the thread finishes, because the class instance will stay with all data intact until the GC junks it. I've used setup properties before, which is why I thought of this. I do think this is better than running a method to get the device handles, save them to a public static ArrayList (yuck!), start the form, via onload event start processing the devices based off the public static ArrayList in a new timer thread, and then onclosing event to close the devices handles and wait for the last timer thread to die. 5. see 1. & 2. 6. Considering that the thread is holding handles to USB devices, I can't make it in the background. If the thread can't finish and exit within 3 seconds (~16-18 loops in the thread) after calling join() and setting the exit flag. Then it is soft locked and wouldn't matter if I killed it. Since the app is closing anyway it's ok to just junk it and the USB port handle will timeout at ~750ms via my driver. The problem here is it's better to allow the thread to finish for it might be witting to e2 on the device. Which is bad if you save to the the device and close the form before it is 100% written.


          -Spacix All your skynet questions[^] belong to solved

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

          Hi Spacix, you're welcome. 3. To yield CPU cycles for the duration of the system tick, a Thread.Sleep(0) is recommended. 4,6. You didn't tell about USB and EE before, I now see why you did what you did. I'm still not convinced there is a need to do it this way tho, AFAIK running timers (i.e. not stopped/disabled) and threads (foreground and background ones) remain active even if you don't have any live references to them any more (except that the last foreground thread reaching its exit will cause app exit). For timers it is well documented; for threads I don't know if/where it is stated explicitly, the only thing I noticed is there is no Thread.Dispose() so I expect the "physical" thread to live on independent of the "logical" Thread object. 7. I would suggest you create a "myUsbDevice" class that encapsulates all relevant code, including the thread stuff, and the dont-interrupt-EE-writing logic. You might give it an IsBusy() or a WaitTillDone() method and give your form a FormClosing event, where you wait until myUsbDevice.IsBusy() returns false or 3 seconds have elasped (easiest is to read DateTime.Now in a yielding loop). :)

          Luc Pattyn [Forum Guidelines] [My Articles]


          This month's tips: - before you ask a question here, search CodeProject, then Google; - the quality and detail of your question reflects on the effectiveness of the help you are likely to get; - use PRE tags to preserve formatting when showing multi-line code snippets.


          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