Solved

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

Posted on 2004-08-27
5
437 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
  • 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

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

762 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

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now