CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 8 of 8

Hybrid View

  1. #1
    Join Date
    Jan 2012
    Location
    India
    Posts
    193

    Problem in creating Threads

    Hi ,

    I am trying to create and test a Thread ..

    Using a code from tutorial ..

    Code:
    namespace ThreadTry
    {
           class Program
           {
    
                    static void Main(string[] args)
    
                    Thread t = new Thread(WriteY); // create thread
    
                    t.Start(); // start thread
                            
                    for (int i = 0; i < 500; i++) Console.Write('S');
                
                
                   for (; ; )
                   {
                            Console.Write('M');
                           // Infinite loop to check thread occurance          
                   }
                
           
    
                  static void WriteY()
                  {
                              Console.WriteLine("    YYYYYYYY   ");
                
                  }
           }
    }

    I need continuously running thread till my application Runs.
    This is just a test program.
    But the thread t is not continuous. It stops after 1/2 r occurances.

    I am using visual C# express 2010 and unable to use Resume .

    Pl guide me , where is the problem. ?

    Thanking you ..
    Last edited by Arjay; May 3rd, 2013 at 11:59 AM. Reason: Added code tags

  2. #2
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Problem in creating Threads

    Please use code tags. Wrap your code with [ Code]code goes here[ /CODE] (minus the spaces).

    You have several problems.

    First of all, the code you've posted is a code fragment and won't compile. You don't have closing braces around the main method. It's important to post complete code to the forum (using code tags) so we can actually see what's going on.

    The second this is NEVER spin with a for loop waiting on something to complete (i.e. for(; { } ). This will only peg your cpu and if you only have a single core system, it will starve other threads. For the purpose of this test, replace the spin loop with Thread.Sleep(30000);

    Now you ask why your thread "It stops after 1/2 r occurances."?

    It does this because this is the way you've coded it. Think of the thread as something that executes a method (e.g. WriteY), and when the method is finished the thread completes. Your WriteY only calls Console.WriteLine one time before the method ends (and the thread is finished). If you want to keep the thread going, you need to add a while loop to the WriteY method:

    Something like:
    Code:
    namespace ThreadTry
    {
      class Program
      {
    
        static void Main(string[] args)
        {  
          Thread t = new Thread(WriteY); // create thread
          t.IsBackground = true;
          t.Start(); // start thread
                            
          for (int i = 0; i < 500; i++)
          {
              Console.Write('S');
    
              Thread.Sleep(10);
          }
    
          Thread.Sleep(30000);
        }
    
        static void WriteY()
        {
          while(true)
          {
              Console.WriteLine("    YYYYYYYY   ");
              Thread.Sleep(100);
          }
        }
      }
    }
    Notice the sleep statements I've added to the code? The big Sleep(30000) is just to wait in the main thread while the worker thread runs. This replaces your spin loop and cause the main method to run for 30 seconds after it leaves the for loop above it.

    The other two small sleeps are just to prevent the cpu from pegging. In a real program, you generally won't put sleeps in your code to prevent high cpu usage. Instead you usually have the thread run freely, do some work, and then wait on an event to do more work.
    Last edited by Arjay; May 3rd, 2013 at 12:20 PM.

  3. #3
    Join Date
    Jan 2012
    Location
    India
    Posts
    193

    Red face Re: Problem in creating Threads

    Thank you Arjay Sir .. I really tried to put tags but missed at some places.
    I will definitely take care of all these things including attaching real program code.

    I tried your code and it worked. Now I will try to implement it in windows form.

    For my actual program I am trying all these features.

    Thank u once again.

  4. #4
    Join Date
    Jan 2012
    Location
    India
    Posts
    193

    Re: Problem in creating Threads

    Arjay Sir , I tried the program with Windows Form . That worked well.

    But again I needed a while loop for Thread Routine. Pl explain that more.

    In actual practice , I will need two threads , one to read data from hardware device and another thread
    to process the data at time intervals of 10ms.
    Will I need the same While Loops in the actual threads ? How to set the time intervals for the threads ?
    by using Sleep command at the execution end ?

    pl guide.

    Thanking you once again

  5. #5
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Problem in creating Threads

    Quote Originally Posted by new_2012 View Post
    Arjay Sir , I tried the program with Windows Form . That worked well.

    But again I needed a while loop for Thread Routine. Pl explain that more.

    In actual practice , I will need two threads , one to read data from hardware device and another thread
    to process the data at time intervals of 10ms.
    Will I need the same While Loops in the actual threads ?
    Yes. Understand if the thread proc method reaches it's end, the thread will stop. You need a while loop (or some other loop) to keep it from ending.

    Quote Originally Posted by new_2012 View Post
    How to set the time intervals for the threads ?
    by using Sleep command at the execution end ?
    The time interval depends on whether you want to include the processing time (i.e. the amount of time spent doing the work). Does the 10ms interval include the work time, or does it just pause 10ms between each time doing work and then the work takes as long as it takes? For example, if we include the work time: say a bit of work takes 2ms and you want to pause a total of 10ms. You would get the current time before starting the work, do the work, retrieve the time again, do a diff (say the work took 2ms) and then pause again for 8ms. Next time around the work might take 3ms, so you would only pause 7ms, and so on. With the other approach, you would simply always pause 10ms regardless of how long the work took. As far as setting the time intervals, I prefer to use a WaitHandle.WaitAny method to do the timeout. The reason being is that I usually include to wait on an exit event, so I can quickly exit a thread (maybe I need to start and stop the thread or just cleanly close the thread because my app is shutting down.

    The code below wakes up every 20 seconds (i.e a simple 20 second delay) and sends a 'ping' message to a message queue which are read on a server and a database record is updated. Btw, the message itself contains a timestamp and the system time between the machine this service runs on and the database are keep in sync via other means.

    Code:
    namespace Iridyn.Common.TimeClock.HGU.Service
    {
        #region Using Directives
    
        using System;
        using System.Collections.Generic;
        using System.Text;
        using System.Threading;
    
        using Iridyn.Common.TimeClock.Common;
        using Iridyn.Common.Threading;
        using System.Messaging;
        using System.Diagnostics;
    
        #endregion Using Directives
    
        public class Ping
        {
            #region Public Methods
    
            public static Ping Create( SyncEventLog eventLog )
            {
                return new Ping( eventLog );
            }
    
            public void Start( Guid serviceID, Guid locationID, int pingInterval )
            {
                _serviceID = serviceID;
    			_locationID = locationID;
                _pingInterval = pingInterval;
    
                CreatePingThread( );
            }
    
            public void Stop( )
            {
                if( null != _pingThread )
                {
                    // Signal the thread to exit
                    _stopEvent.Set( );
    
                    // Close the thread
                    _pingThread = null;
                }
            }
    
            #endregion Public Methods
    
            #region Private Methods
    
            private Ping(SyncEventLog eventLog) { _eventLog = eventLog; }
    
            private void CreatePingThread( )
            {
                if( null == _pingWaitHandles )
                {
                    _pingWaitHandles = new WaitHandle[ ] { _stopEvent };
                }
    
                if( null == _pingThread )
                {
                    _pingThread = new Thread( new ThreadStart( PingThreadProc ) );
                    _pingThread.Start( );
                }
            }
    
            /// <summary>
            /// Thread proc wakes up on the specified interval and calls the
            /// Ping method to tell the timeclock database this service is alive.
            /// </summary>
            private void PingThreadProc( )
            {
                while( true )
                {
                    switch( WaitHandle.WaitAny( _pingWaitHandles, _pingInterval * 1000, false ) )
                    {
                    // Stop Event: exit thread
                    case Constants.StopEvent:
                        return;
    
                    // Timeout event: ping that we're alive
                    case WaitHandle.WaitTimeout:
                        try
                        {
                            using( MessageQueue mq = new MessageQueue( AppConfig.Connections.Queue.TimeClockEventQueue ) )
                            {
    							mq.Send( TimeClockPing.CreateMessage( _serviceID, _locationID ) );
                            }
                        }
                        catch( Exception e )
                        {
                            _eventLog.WriteEntry( e.Message + Constants.NewLine + Constants.NewLine + e.StackTrace, EventLogEntryType.Error );
                        }
                        break;
                    }
                }
            }
    
            #endregion Private Methods
            
            #region Private Fields
    
            private WaitHandle[ ] _pingWaitHandles = null;
            private Thread _pingThread = null;
    
            /// <summary>
            /// Stop Event. This event is set when the Service OnStop method
            /// has been called and forces the ping thread to exit
            /// </summary>
            private AutoResetEvent _stopEvent = new AutoResetEvent( false );
    
            private int _pingInterval = 20;
            private Guid _serviceID = Guid.Empty;
    		private Guid _locationID = Guid.Empty;
    
            private SyncEventLog _eventLog = null;
    
            #endregion Private Fields
    
        }
    }
    I've attached this code because it uses the while loop in the thread and shows how to exit cleanly from the thread using an event.

  6. #6
    Join Date
    Jan 2012
    Location
    India
    Posts
    193

    Re: Problem in creating Threads

    Thankx a lot Arjay Sir ..

    I will read and study the attached code very carefully.

    Now I think I can handle Threading in good way.

    My Thread code gets executed in 1ms so I have decided
    to take a pause of 10ms ( just 10 times).

    These guidelines play a very important role in development
    cycles.

  7. #7
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Problem in creating Threads

    I might not have mentioned it before, but thread 'wake-up' times are approximate. For example, if you call the WaitHandle.WaitAny method with a 100ms second timeout (or call Sleep(100)), there is no guarantee that the thread will wake up in exactly 100ms. This is because of how the thread scheduler works and depends on several factors such as if there are other higher priority threads scheduled in the system (they'll run first), or other threads with equal priority (these will run with your thread in a round robin fashion).

    The bottom line is your thread could wait up at very close to 100ms, but it may be some indeterminate longer time as well.

    For multi-threaded programming, understanding a the details is vital. A great book to learn all this is Programming Applications for Microsoft Windows by Jeffrey Richter. The book has code samples in C++ (instead of C#), but it is excellent.

  8. #8
    Join Date
    Jan 2012
    Location
    India
    Posts
    193

    Re: Problem in creating Threads

    Thank you Arjay Sir .. I will definitely get that book . Pl do suggest me some
    more good books.
    Now I am studying GDI+ ..
    I have not yet planned for WPF but next month , after completing C# and GDI+
    I will target for that.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured