Solved

C# Thread Sleep vs. Synchronize vs. ThreadPool ???

Posted on 2004-08-27
5
460 Views
Last Modified: 2010-08-05
The code below works quite well although I must admit I don't completly understand it. I placed the Class1 last so the Thread.Sleep would control it. The Class1 run most of the time while Class1 has a breif but effective interval to complete it's task. I think the code I have may prove to be unpredicable in the long run..........

1. Why would C# use syntax like 'Thread.Sleep' instead of say 't1.Sleep' or t2.Sleep', etc...???
2. What 'delay' or timing effect does the 'for' statement have???
3. Would Sychronize or ThreadPool work more efficiently???  

private void Form1_Load(object sender, System.EventArgs e)
      {
            Class2 objClass2 = new Class2();
            Thread t2 = new Thread(new ThreadStart(objClass2.StartLookUp));
            t2.Start();

            Class1  objClass1 = new Class1();
            Thread t1 = new Thread(new ThreadStart(objClass1.StartServer));
            t1.Start();

            for (int i=0; i < 10; i++)
            {
                  Thread.Sleep(1000);
            }
                }
0
Comment
Question by:kvnsdr
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
5 Comments
 
LVL 19

Expert Comment

by:drichards
ID: 11916113
1. Why would C# use syntax like 'Thread.Sleep' instead of say 't1.Sleep' or t2.Sleep', etc...???

Because Thread.Sleep() is a static method of Thread that puts the current thread to sleep.  You cannot tell another thread to sleep.  You can suspend another thread, however:  t1.Suspend();

2. What 'delay' or timing effect does the 'for' statement have???

It just does the 1 second Sleep 10 times.  Unless you're doing something else in the loop, it's really not any different than Thread.Sleep(10000) without the loop.  The one difference is that the OS will have to do a bunch of extra context switches to process 10 sleeps.  Instead of going to sleep and waking up only one time, the thread will have to be put to sleep and reactivated 10 times.  This adds a bit of overhead.  The net effect is that the main thread stops for 10 seconds.

3. Would Sychronize or ThreadPool work more efficiently???  

I'm not sure exactly what you're trying to do here.  You said "I placed the Class1 last so the Thread.Sleep would control it", but that doesn't have anything to do with the sleep.  If you're trying to wait for t1 to do something, you can do Thread.Join:

    t1.Join(); // Waits until t1 has completed
    t1.Join(1000); // Waits until either t1 completes or 1 second has elapsed (1000 milliseconds)

If you're trying to guarantee that t1 has executed for at least some minimum time, you'll need another approach altogether.
0
 
LVL 1

Author Comment

by:kvnsdr
ID: 11918098

I've read that 'Join' only triggers when the Thread is terminiated.

Q. Is terminated the same terminology as 'Abort'???

None the less, I'm using the simple Thread.Sleep(500) with great success.
0
 
LVL 19

Expert Comment

by:drichards
ID: 11918221
There are three versions of Thread.Join.  I show two of them in previous example.  The one with no parameters will only end when the thread terminates.  It's equivalent to doing the second version with the timeout value set to 'System.Threading.Timeout.Infinite'.

Sleep is great until your thread takes more than half a second to execute and your main routine continues along thinking it has finished.  If that's not an issue for you, then Sleep will work just fine.  Join with a wait parameter at least lets you know that the thread is still executing.  It will return True if the thread is done and false if the wait has timed out.  This at least alerts you to the fact your thread is not done and lets you take corrective action.

Instead of:

          for (int i=0; i < 10; i++)
          {
               Thread.Sleep(1000);
          }

you could do:

    bool done = t1.Join(1000); // Wait for 1 second or until thread finishes
    if ( !done  )
    {
        // Thread did not finish - wait some more, abort thread, or do nothing and continue
    }
0
 
LVL 1

Author Comment

by:kvnsdr
ID: 11919141
You've earned your points.  I only have one more question before closing this topic I started. I've read that it takes more processor time and wastes memory having to continually create and destoy threads.

Q. Just wondering if Thread Pooling is the most efficient method of handling two or more threads?
0
 
LVL 19

Accepted Solution

by:
drichards earned 250 total points
ID: 11919192
If you're going to be continually spinning up new threads then thread pooling makes a lot of sense.  If it's something you'll be doing only a few times or very sporadically over the life of the program, then just making new ones is better.  You'll have to analyze what you're doing with the threads to see which makes sense.  It's not apparent from the little code snippet in your question.
0

Featured Post

Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
In this video we outline the Physical Segments view of NetCrunch network monitor. By following this brief how-to video, you will be able to learn how NetCrunch visualizes your network, how granular is the information collected, as well as where to f…
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…

623 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question