Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / Languages / C# / March 2008

Tip: Looking for answers? Try searching our database.

Threading

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
davebythesea - 28 Mar 2008 10:37 GMT
Hi folks,

In the following code I create a thread and start it. I then call
Thread.Sleep() within that thread. Will this cause the thread I created to
Sleep or will it cause the main application Thread to sleep? I'm hoping it
will cause the created Thread to sleep...

class A
{

    private Thread thread;

    public A()
    {
        thread = new Thread(new ThreadStart(Sync));

        thread.IsBackground = true;
        thread.Priority = ThreadPriority.Normal;
        thread.Start();
    }

    private void Sync()
    {
        while (true)
        {
            Thread.Sleep(10000);

            // do stuff
        }
    }
}
Peter - 28 Mar 2008 10:45 GMT
> Hi folks,
>
> In the following code I create a thread and start it. I then call
> Thread.Sleep() within that thread. Will this cause the thread I
> created to Sleep or will it cause the main application Thread to
> sleep? I'm hoping it will cause the created Thread to sleep...

Thread.Sleep causes the current thread to block - that means the thread
calling the Thread.Sleep method (ie your thread).

Incidentally I wonder if someone can answer me if the following code is
an ok idea?

I set up a "stopEvent" like this:
private ManualResetEvent[] stopEvent = new ManualResetEvent[1];

Then in my thread method I have the following loop:

for (; ; )
{
 int index = WaitHandle.WaitAny(stopEvent, 10000, false);
 if (index != WaitHandle.WaitTimeout)
 {
   break;
 }

 // do stuff ...
}

The point being I can then have a "Stop" method to stop the thread,
like this:

stopEvent[0].Set();

Thanks,
Peter

--
Marc Gravell - 28 Mar 2008 10:54 GMT
Not sure why you need the array and WaitAny - and indeed the other problem
is that it will be spending lots of time waiting, and not much time *doing*
anything. It depends what the system is - if you just want an exit
condition, a volatile bool might suffice, or a [Manual|Auto]ResetEvent using
the overload of WaitOne that accepts a timeout and returns a bool to
indicate whether the flag was set.
In other scenarios Monitor.Pulse and Monitor.Wait might be used to help
synchronize - especially in scenarios like producer/consumer queues when you
expect the queue to be empty, but after adding an item you want the consumer
thread to wake up immediately and do something useful (and likewise when
terminating it).

Marc
Peter - 28 Mar 2008 11:04 GMT
> Not sure why you need the array and WaitAny - and indeed the other
> problem is that it will be spending lots of time waiting, and not
[quoted text clipped - 7 lines]
> want the consumer thread to wake up immediately and do something
> useful (and likewise when terminating it).

Hi, thanks for your reply.

I do want the thread to wait, do something, and wait again... The wait
is configurable, could be many minutes or an hour or so. Could this be
a problem with such a long wait? Are there better ways to implement a
"do something every 30 minutes" function than using a thread with a 30
minute sleep?

The problem with using a bool flag is that it will wait for the timeout
before checking the flag and stopping (I think), whereas if I have a
"waitany" then the wait will cease as soon as the stopEvent is set.

I will look at WaitOne to see what it does...

/Peter

--
davebythesea - 28 Mar 2008 11:14 GMT
Thanks for the confirmation Peter.

I had considered using a bool to control the running of the Thread ie.

private bool bRun = true;
private void Sync()
    {
        while (bRun)
        {
            Thread.Sleep(10000);

            // do stuff
        }
    }

private void StopThread()
    {
        bRun = false;
    }

But then if you want to start the Thread again, a call to Start will throw
an Exception?

> Incidentally I wonder if someone can answer me if the following code is
> an ok idea?
[quoted text clipped - 22 lines]
> Thanks,
> Peter
Jon Skeet [C# MVP] - 28 Mar 2008 11:22 GMT
> Thanks for the confirmation Peter.
>
[quoted text clipped - 15 lines]
>         bRun = false;
>     }

That will only work if bRun is volatile. See
http://pobox.com/~skeet/csharp/threads/volatility.shtml

> But then if you want to start the Thread again, a call to Start will throw
> an Exception?

You can't restart a thread which has terminated - you'd need to create
a new thread instead.

Signature

Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet   Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk

davebythesea - 28 Mar 2008 11:29 GMT
Thanks Jon, this is very useful for me.

Dav

> > Thanks for the confirmation Peter.
> >
[quoted text clipped - 24 lines]
> You can't restart a thread which has terminated - you'd need to create
> a new thread instead.
Marc Gravell - 28 Mar 2008 10:47 GMT
That is correct. Sync will be executed by the worker thread, so the Sleep
applies to the worker thread; the main thread will carry on doing whatever
without interruption.

Marc
davebythesea - 28 Mar 2008 10:57 GMT
Thankyou for the confirmation Marc,

David

> That is correct. Sync will be executed by the worker thread, so the Sleep
> applies to the worker thread; the main thread will carry on doing whatever
> without interruption.
>
> Marc

Rate this thread:







Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.