473,396 Members | 2,024 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Break thread sleep

Hello group.

I have thread in which I perform specific task in loop. I can specify,
by check box, in what periods of time that task should be done, ex.
instantly, with 5min break, with 15min break etc. For now I had it
done in way like that.

while(true)
{
period = checkIfPeriodChanged();
...
performTask
...
Sleep(period);
}

That works fine, until I want to change period time. For example, when
I set period to 15min, and after performTask I change it again to
1min, I have to wait all ~15min, to put my new settings (1min) into
operation. Is there any way, to break Sleep(period), or should I do it
in very different way? I looked at System.Threading.Timer, but i'm not
sure if it'll be working, becouse I don't know how long time execute
performTask will take (differences can be rather wide - from couple
seconds to few minutes).

I will be gratefull for any kind of help.
Masanobu Suga

Oct 3 '07 #1
15 5635
On Oct 3, 11:22 am, suga.masan...@gmail.com wrote:

<snip>
That works fine, until I want to change period time. For example, when
I set period to 15min, and after performTask I change it again to
1min, I have to wait all ~15min, to put my new settings (1min) into
operation. Is there any way, to break Sleep(period), or should I do it
in very different way?
Instead of using Thread.Sleep, use Monitor.Wait, "breaking" it with
Monitor.Pulse.

Jon

Oct 3 '07 #2
<su***********@gmail.comwrote in message
news:11**********************@19g2000hsx.googlegro ups.com...
Hello group.

I have thread in which I perform specific task in loop. I can specify,
by check box, in what periods of time that task should be done, ex.
instantly, with 5min break, with 15min break etc. For now I had it
done in way like that.

while(true)
{
period = checkIfPeriodChanged();
...
performTask
...
Sleep(period);
}

That works fine, until I want to change period time. For example, when
I set period to 15min, and after performTask I change it again to
1min, I have to wait all ~15min, to put my new settings (1min) into
operation. Is there any way, to break Sleep(period), or should I do it
in very different way? I looked at System.Threading.Timer, but i'm not
sure if it'll be working, becouse I don't know how long time execute
performTask will take (differences can be rather wide - from couple
seconds to few minutes).

I will be gratefull for any kind of help.
Masanobu Suga

I suppose *performTask* starts another thread to run the task, why not
simply use Thread.Join instead of Sleep?

Willy.

Oct 3 '07 #3
su***********@gmail.com wrote:
[...]
while(true)
{
period = checkIfPeriodChanged();
...
performTask
...
Sleep(period);
}

That works fine, until I want to change period time. For example, when
I set period to 15min, and after performTask I change it again to
1min, I have to wait all ~15min, to put my new settings (1min) into
operation. Is there any way, to break Sleep(period), or should I do it
in very different way?
A couple of suggestions:

1) If you want to block with a timeout but still be alertable, you
can use a WaitHandle (eg AutoResetEvent) and call WaitOne() with a
timeout (eg "period"). This is similar to the Monitor method Jon
mentions; it's just a different way of doing the same thing (assuming
you use the Monitor.Wait() overload with a timeout).

2) IMHO, if the goal is to run a specific task at specific
intervals, and you want the user to be able to modify the interval, your
current implementation isn't really the best anyway.

I think it would be better to just use the Forms.Timer class to have an
event raised on a specific time interval, and then use a
BackgroundWorker or similar to run the task. Rather than having a
thread sitting around waiting to see if the time period changes or
expires, instead you would simply have the UI update the timer period in
response to user actions, and in the event raised by the timer object
assign a thread (via BackgroundWorker or similar) to actually do the task.

Pete
Oct 3 '07 #4
On 3 Pa , 12:28, "Jon Skeet [C# MVP]" <sk...@pobox.comwrote:
Instead of using Thread.Sleep, use Monitor.Wait, "breaking" it with
Monitor.Pulse.
That's first class solution but I still have some problems. If I put
Monitor.Wait in loop and break it with Monitor.Pulse putted in event
(radio button click) I won't have continuity - after one iteration
loop will wait for pulse which is only in click event, so only if I'll
click radio button loop will coutinue (only one iteration again). I
thought about adding aditional pulse to other event, like 'add to
list', but I'm not sure yet, if it'll be working good. If that's not
good idea, and I'm still not using Monitor.Wait/Pulse in a good way,
please correct me.

Oct 5 '07 #5
On 3 Pa , 12:41, "Willy Denoyette [MVP]" <willy.denoye...@telenet.be>
wrote:
I suppose *performTask* starts another thread to run the task
It's not. performTask is using specific method from 'add reference'
library. I'm not sure if I really need to make separate thread for it.
(And tell you the truth I don't even know how. That perforTask takes
some arguments, and while running it's sending/returning some
information to form).
Oct 5 '07 #6
On 3 Pa , 18:48, Peter Duniho <NpOeStPe...@NnOwSlPiAnMk.comwrote:
IMHO, if the goal is to run a specific task at specific
intervals, and you want the user to be able to modify the interval, your
current implementation isn't really the best anyway.
Your suggestions are really nice BUT... (always that but ;-) ).
The trick is that I don't know how long time would single loop takes.
So I don't know when use Timer to raise task, after I did it once.
Perhaps in longer periods (like 15min) it won't be a problem, as task
won't take so long to perform, but if I set that it should be
performed without brakes (task, 0 sec break, task, 0 sec break etc.) I
think Timer won't work, as it don't know how long time task will take
(how long it should wait). Generally my break before performing tasks
is performTaskTime + userDefinedBreakTime.

Oct 5 '07 #7
On Oct 5, 2:36 pm, suga.masan...@gmail.com wrote:
On 3 Pa , 12:28, "Jon Skeet [C# MVP]" <sk...@pobox.comwrote:
Instead of using Thread.Sleep, use Monitor.Wait, "breaking" it with
Monitor.Pulse.

That's first class solution but I still have some problems. If I put
Monitor.Wait in loop and break it with Monitor.Pulse putted in event
(radio button click) I won't have continuity - after one iteration
loop will wait for pulse which is only in click event, so only if I'll
click radio button loop will coutinue (only one iteration again). I
thought about adding aditional pulse to other event, like 'add to
list', but I'm not sure yet, if it'll be working good. If that's not
good idea, and I'm still not using Monitor.Wait/Pulse in a good way,
please correct me.
It's not clear to me what the problem is, I'm afraid. Could you post a
short but complete program that demonstrates the issue? See
http://pobox.com/~skeet/csharp/complete.html

Jon

Oct 5 '07 #8
<su***********@gmail.comwrote in message
news:11*********************@r29g2000hsg.googlegro ups.com...
On 3 Pa , 12:41, "Willy Denoyette [MVP]" <willy.denoye...@telenet.be>
wrote:
>I suppose *performTask* starts another thread to run the task

It's not. performTask is using specific method from 'add reference'
library. I'm not sure if I really need to make separate thread for it.
(And tell you the truth I don't even know how. That perforTask takes
some arguments, and while running it's sending/returning some
information to form).



Well it looks like you are calling a method, that in turn calls you back to
update the form.
If the above is correct, then I need some more info:
1. What kind of library is this, this is, what are you adding with "add
reference"?
2. On what thread are you calling this "performTask", is it on the UI thread
(I hope it's not) or on another thread (I guess it's not) ?

Willy.

Oct 5 '07 #9
su***********@gmail.com wrote:
On 3 Pa , 18:48, Peter Duniho <NpOeStPe...@NnOwSlPiAnMk.comwrote:
>IMHO, if the goal is to run a specific task at specific
intervals, and you want the user to be able to modify the interval, your
current implementation isn't really the best anyway.

Your suggestions are really nice BUT... (always that but ;-) ).
The trick is that I don't know how long time would single loop takes.
Not really a problem at all. You just need to decide what you want to
do about it.
So I don't know when use Timer to raise task, after I did it once.
If you have a requirement to not start a new task while the current one
is executing, then you need to decide how exactly you want to handle
that case. There are at least two behavior choices:

1) You want the task to be run on specific intervals, and if it's
already running when an interval has expired, just wait for the next
interval to try again.

2) You want the task to be run no more frequently than a specific
interval, but if an interval expires while the task is still being
performed, you want the next iteration of that task to happen
immediately when the current one has completed.

Both options are easily implemented. In the first scenario, you would
simply maintain a volatile flag indicating whether the task is currently
running or not. You'd set the flag when starting the task, and clear it
when the task completes. Then you just look at the flag before starting
the task, and don't bother starting it if it's already set.

In the second scenario, the easiest solution IMHO would be to use a
WaitHandle. You'd have a regular thread (not BackgroundWorker) that
just sits in a loop waiting on the WaitHandle, and doing the processing
when the handle is set (I'd use an AutoResetEvent for convenience).
Then each time the timer interval expires, you simply set the
WaitHandle. If the task is already ongoing, this will ensure that the
next time it waits on the WaitHandle, it simply continues rather than
actually blocking. If the task isn't already ongoing, then the thread
will be waiting on the WaitHandle and setting it will release the thread
so that it can do the processing you want.

I think one of those two behaviors are most likely to fit your needs.
But if not, you simply need to think about what behavior _would_ fit
your needs and then implement it.
Perhaps in longer periods (like 15min) it won't be a problem, as task
won't take so long to perform, but if I set that it should be
performed without brakes (task, 0 sec break, task, 0 sec break etc.) I
think Timer won't work, as it don't know how long time task will take
(how long it should wait). Generally my break before performing tasks
is performTaskTime + userDefinedBreakTime.
Just to clarify: the way I read that last sentence is that the interval
between initiation of the performance of your task is variable, and
depends on the user-defined time _and_ the actual time it took to
perform the task.

For example, assuming the user has asked for 10 second intervals, but
the task performance time is variable, you might have a sequence that
looks like this:

Time Activity
----- ------------
0 s perform task, 3 seconds
3 s wait 10 seconds
13 s perform task, 2 seconds
15 s wait 10 seconds
25 s perform task, 8 seconds
33 s wait 10 seconds

etc.

If that's the case, I really don't see what the problem is. That's a
trivial behavior to implement. I think all of us assumed that you
wanted some timing independent of the length of time it takes to
actually perform the task, and our answers have been directed to that goal.

If the answers haven't explained the issue to you well enough yet, it
seems to me you need to consider trying to rephrase your original
question so that it is much more clear about what you actually want to
accomplish.

Pete
Oct 5 '07 #10
On 5 Pa , 20:37, Peter Duniho <NpOeStPe...@NnOwSlPiAnMk.comwrote:
1) You want the task to be run on specific intervals, and if it's
already running when an interval has expired, just wait for the next
interval to try again.

2) You want the task to be run no more frequently than a specific
interval, but if an interval expires while the task is still being
performed, you want the next iteration of that task to happen
immediately when the current one has completed.
These two solutions are really good and simple in theory, and I'm
little bit embrassed I didn't think about it in that way.
In the second scenario, the easiest solution IMHO would be to use a
WaitHandle. You'd have a regular thread (not BackgroundWorker) that
just sits in a loop waiting on the WaitHandle, and doing the processing
when the handle is set (I'd use an AutoResetEvent for convenience).
Then each time the timer interval expires, you simply set the
WaitHandle. If the task is already ongoing, this will ensure that the
next time it waits on the WaitHandle, it simply continues rather than
actually blocking. If the task isn't already ongoing, then the thread
will be waiting on the WaitHandle and setting it will release the thread
so that it can do the processing you want.
That is solution which nicely fit to my problem, and should solve it
in a good, simple way. I'll do it and report if I find any problems.

Thank you very much for your help.

Oct 11 '07 #11
On Oct 12, 8:27 am, Peter Duniho <NpOeStPe...@NnOwSlPiAnMk.comwrote:

<snip>

(Thanks for the reference)
This remark says that this requirement exists only on "some hosts of the
CLR", and calls out specifically SQL Server "Yukon". However, given the
admonishments I've seen about not generally assuming that a managed
thread is the same as an OS thread, I would say that unless you know for
sure your code is NOT going to run in such an environment (and who knows
what versions of .NET will introduce that behavior later?), it's better
to be safe than sorry.
Hmm. I think it also depends on what it means by "before blocking on".

I'll mail Joe Duffy tonight and see what he thinks.

Jon

Oct 12 '07 #12
Willy Denoyette [MVP] wrote:
[...] Sure, if you implement your own WaitHandle derived types or *locks*,
based on thread affinitized OS object handles or Critical Sections, then
you need to make sure you don't move to another thread.
Well, the docs are clearly not talking about user-defined types. It
specifically calls out "any .NET Framework type".

I do hope you're correct that the docs are just plain wrong. It seems
like a silly requirement to me. But it _is_ in the docs; it would be
nice to know for sure what the truth is.

Pete
Oct 12 '07 #13
Peter Duniho <Np*********@NnOwSlPiAnMk.comwrote:
Willy Denoyette [MVP] wrote:
[...] Sure, if you implement your own WaitHandle derived types or *locks*,
based on thread affinitized OS object handles or Critical Sections, then
you need to make sure you don't move to another thread.

Well, the docs are clearly not talking about user-defined types. It
specifically calls out "any .NET Framework type".

I do hope you're correct that the docs are just plain wrong. It seems
like a silly requirement to me. But it _is_ in the docs; it would be
nice to know for sure what the truth is.
I'll still mail Joe Duffy. He's usually fabulous about clearing up this
kind of thing :)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Oct 12 '07 #14
"Peter Duniho" <Np*********@NnOwSlPiAnMk.comwrote in message
news:13*************@corp.supernews.com...
Willy Denoyette [MVP] wrote:
>[...] Sure, if you implement your own WaitHandle derived types or
*locks*, based on thread affinitized OS object handles or Critical
Sections, then you need to make sure you don't move to another thread.

Well, the docs are clearly not talking about user-defined types. It
specifically calls out "any .NET Framework type".

I do hope you're correct that the docs are just plain wrong. It seems
like a silly requirement to me. But it _is_ in the docs; it would be nice
to know for sure what the truth is.

Pete

IMO the docs are wrong, the latest MSDN docs (VS2008 MSDN) have this
sentence removed, and Yukon is now SQL2005 (which will confuse people when
SQL2008 hits the streets). These API's where added late in the Whidbey
cycle, a lot of changes were necessary because of the removal of fiber
support in the CLR , support which was entirely moved to the SQL2005 (Yukon)
host.

Another reason why I believe they are wrong is found in the Mutex class
(mutants have thread affinity), it calls BeginThreadAffinity on your behalf
when the Mutex gets created and BeginThreadAffinity when the Mutex gets
Released. Note that these internal calls result in a NOP when the CLR is not
hosted in a process that doesn't care about managing his own threads, the
CLR doesn't do anything significant when you call this API in a non hosted
environment.
All other WaitHandle derived types do not wrap thread affinitized OS
objects.

Willy.

Oct 12 '07 #15
Jon Skeet [C# MVP] wrote:
[...]
>I do hope you're correct that the docs are just plain wrong. It seems
like a silly requirement to me. But it _is_ in the docs; it would be
nice to know for sure what the truth is.

I'll still mail Joe Duffy. He's usually fabulous about clearing up this
kind of thing :)
That would be great. I'd also like to see a single, definitive
statement regarding what assumptions one can make, if any, regarding the
relationship between a managed thread and an unmanaged thread.

I can see the advantage in having them be separate concepts, but it
seems to me that if this is going to be the case, the framework should
hide those implementation details from us. The framework should be
making things _simpler_, not more complicated.

Pete
Oct 12 '07 #16

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

38
by: Anthony Baxter | last post by:
On behalf of the Python development team and the Python community, I'm happy to announce the release of Python 2.3.1 (final). Python 2.3.1 is a pure bug fix release of Python 2.3, released in...
26
by: news.microsoft.com | last post by:
Hi, Currently I have a thread thats spinning and doing a Thread.Sleep(someTime). I was thinking of changing this to Thread.Sleep(Timeout.Infinite); then when I have actual data in a...
8
by: Cider123 | last post by:
I ran into a situation where my Window Service had to process 100,000+ files, when I first noticed I needed to tweak various routines. Everything runs fine, but here's what I ran into: In the...
4
by: Matthew Groch | last post by:
Hi all, I've got a server that handles a relatively high number of concurrent transactions (on the magnitude of 1000's per second). Client applications establish socket connections with the...
6
by: d_well | last post by:
Hi, I use a method of a dll and this method use 3 or 4 seconds to calculate a result. This method run into a thread. I noticed when I am runing this method, the other thread cannot be run as...
9
by: Chris Dunaway | last post by:
According to the docs, calling Thread.Sleep(0) causes the thread to be "suspended to allow other waiting threads to execute." What happens if I call Thread.Sleep(500)? Do other threads not get a...
5
by: fniles | last post by:
I am having problem with thread. I have a Session class with public string variable (called Message) that I set from my Main program. In the session class it checks for the value of Message...
0
by: Buckaroo Banzai | last post by:
Hello, newbie here... I'm writing this program but when I click the start button which should initiate either the Hare or the Tortoise, it does not, this is the first time I use threads, so the...
9
by: =?Utf-8?B?anAybXNmdA==?= | last post by:
I've got a routine that builds a table using different queries, different SQL Tables, and adding custom fields. It takes a while to run (20 - 45 seconds) so I wrote a thread to handle the table...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.