469,265 Members | 1,995 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,265 developers. It's quick & easy.

How do I wait until myVar == true

Howdy everybody!

How do I do the following...

while (myVary != true){};

Obviously I do not want to use 100% of the processor to stay in this
infinite loop till myVar == true. But wait do I do?

Thanks yal!
- Coder ;)

Jan 19 '06 #1
18 48122
Perhaps more information would be in order -- like what are you trying
to do ..... if you are just trying to wait for the condition to be true
-- you can use an AutoResetEvent and sit on it with WaitOne .... if you
are doing work inside the loop -- it will be more efficient and safer
(assuming this is part of some multi-threaded code) to use a numeric
argument and Interlocked.Read ...

John

Coder wrote:
Howdy everybody!

How do I do the following...

while (myVary != true){};

Obviously I do not want to use 100% of the processor to stay in this
infinite loop till myVar == true. But wait do I do?

Thanks yal!
- Coder ;)

Jan 20 '06 #2
Coder <co*****@yahoo.com> wrote:
Howdy everybody!

How do I do the following...

while (myVary != true){};

Obviously I do not want to use 100% of the processor to stay in this
infinite loop till myVar == true. But wait do I do?


Firstly, I'd suggest writing the condition as !myVar. Otherwise you
might could make a typo, remove the "!" and end up with an assignment
you didn't mean.

Secondly, you should consider the threading issues. I assume that
another thread is going to change the value of myVar? You need to make
sure that either myVar is volatile or use a property which includes
locking. See
http://www.pobox.com/~skeet/csharp/t...latility.shtml for details
on why this is necessary.

Okay, so what to do about waiting? You could just call Thread.Sleep -
but that means you won't wake up as quickly as you might want to, and
you'll still have to go round the loop checking it each time.

What you actually want is either a Manual/AutoResetEvent, or to use
Monitor.Wait/Pulse - a way of saying "Sleep until I'm told to wake up
by this object". For more information on those topics, see
http://www.pobox.com/~skeet/csharp/t...eadlocks.shtml (half way)
and http://www.pobox.com/~skeet/csharp/t...thandles.shtml

--
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
Jan 20 '06 #3
Whether you do it in the main thread or not, I would write it like this:

while (!myVary) {
System.Threading.Thread.Sleep(250); // pause for 1/4 second;
};

That way you give the CPU back to the O/S without taking up resources.
Jan 20 '06 #4
Thread.SpinWait(1) is another option if you just want to yield for a cycle
Gabriel Magaña wrote:
Whether you do it in the main thread or not, I would write it like this:

while (!myVary) {
System.Threading.Thread.Sleep(250); // pause for 1/4 second;
};

That way you give the CPU back to the O/S without taking up resources.

Jan 20 '06 #5
Thanks everyone!!!

I like the option of System.Threading.Thread.Sleep(250); best for me
needs.

Let me konw what you think. Here are my needs...my application deals
with interacting with equipment. I have different batches of materail
that the equipment processes. I want to introduce the first batch.
Then, when the second batch arrives, I want to introduce it but wait to
run it till the first batch is done. I would like to do this in a
synchronous fashion in my code rather than wait for an event
asynchronously. Therefore, I would like to pause in my synchronous
line of code till firstBatchComplete == true.

Jan 20 '06 #6
In that case, you should either process the data in a separate thread, or if
you want simple, then wait for the process to finish in the main thread but
do something like

while (!myVary) {
System.Threading.Thread.Sleep(50); // pause for 1/20 second
Application.DoEvents();
};

That way your app does not appear to be locked up (ie, you can move, resize,
etc... the window while waiting for your process to finish). This may or
may not be a problem, depending on how long you have to wait for the data to
finish processing.

"Coder" <co*****@yahoo.com> wrote in message
news:11**********************@g14g2000cwa.googlegr oups.com...
Thanks everyone!!!

I like the option of System.Threading.Thread.Sleep(250); best for me
needs.

Let me konw what you think. Here are my needs...my application deals
with interacting with equipment. I have different batches of materail
that the equipment processes. I want to introduce the first batch.
Then, when the second batch arrives, I want to introduce it but wait to
run it till the first batch is done. I would like to do this in a
synchronous fashion in my code rather than wait for an event
asynchronously. Therefore, I would like to pause in my synchronous
line of code till firstBatchComplete == true.

Jan 20 '06 #7
Also, if you do call DoEvents() within your loop do additional
debugging/coding so you don't let the user do something they should not be
doing while you are waiting for the processing to finish, such as pressing a
button again (start the process again for example), close the application,
etc...
Jan 20 '06 #8
Gabriel,

Thanks! I'm greatful for you email. I actually want my thread to be
active so that it can process the other requests coming in. I'm
assuming sleep pauses my thread...which I don't want. Therefore, I
will create a new thread that sleeps until the first thread sets the
flag to true.

Let me know what you think.

Jan 20 '06 #9
Gabriel Magaña <no*****@no-spam.com> wrote:
In that case, you should either process the data in a separate thread, orif
you want simple, then wait for the process to finish in the main thread but
do something like

while (!myVary) {
System.Threading.Thread.Sleep(50); // pause for 1/20 second
Application.DoEvents();
};

That way your app does not appear to be locked up (ie, you can move, resize,
etc... the window while waiting for your process to finish). This may or
may not be a problem, depending on how long you have to wait for the datato
finish processing.


Using DoEvents() in a loop like that is a bad idea. Something else is
clearly going to set myVar to true; instead of going round a loop, that
something else should just call BeginInvoke on the form, so that the UI
thread picks up the fact that there's new data.

Application.DoEvents() is very rarely needed in .NET code - it was a
hack to keep UIs responsive when multi-threading was hard to get at.

--
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
Jan 20 '06 #10
Coder <co*****@yahoo.com> wrote:
Thanks! I'm greatful for you email. I actually want my thread to be
active so that it can process the other requests coming in. I'm
assuming sleep pauses my thread...which I don't want. Therefore, I
will create a new thread that sleeps until the first thread sets the
flag to true.

Let me know what you think.


It's not entirely clear what you want to do. You might consider a
producer/consumer queue, however, where one thread adds work items and
another takes them off as they arrive. See half way down
http://www.pobox.com/~skeet/csharp/t...eadlocks.shtml
for a code example.

(This shouldn't be in the UI thread though.)

--
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
Jan 20 '06 #11
On Fri, 20 Jan 2006 06:59:22 -0000, Jon Skeet [C# MVP]
<sk***@pobox.com> wrote:
Application.DoEvents() is very rarely needed in .NET code - it was a
hack to keep UIs responsive when multi-threading was hard to get at.


It's also super-dangerous since Windows might call back to any old
method wired up as a Windows event handler (e.g. user interface) while
you're waiting for DoEvents to return. This can completely trash your
internal application state if you're not careful.
--
http://www.kynosarges.de
Jan 20 '06 #12
Please no DoEvents(), take a look at Christoph's reply and take it
seriously.
Also, calling DoEvents in a thread that has no UI, makes no sense (it turns
into a NOP).
This is one of the things that should not have been in the framework, but I
guess the VB folks insisted....

Willy.

"Gabriel Magaña" <no*****@no-spam.com> wrote in message
news:uH**************@TK2MSFTNGP11.phx.gbl...
| In that case, you should either process the data in a separate thread, or
if
| you want simple, then wait for the process to finish in the main thread
but
| do something like
|
| while (!myVary) {
| System.Threading.Thread.Sleep(50); // pause for 1/20 second
| Application.DoEvents();
| };
|
| That way your app does not appear to be locked up (ie, you can move,
resize,
| etc... the window while waiting for your process to finish). This may or
| may not be a problem, depending on how long you have to wait for the data
to
| finish processing.
|
| "Coder" <co*****@yahoo.com> wrote in message
| news:11**********************@g14g2000cwa.googlegr oups.com...
| > Thanks everyone!!!
| >
| > I like the option of System.Threading.Thread.Sleep(250); best for me
| > needs.
| >
| > Let me konw what you think. Here are my needs...my application deals
| > with interacting with equipment. I have different batches of materail
| > that the equipment processes. I want to introduce the first batch.
| > Then, when the second batch arrives, I want to introduce it but wait to
| > run it till the first batch is done. I would like to do this in a
| > synchronous fashion in my code rather than wait for an event
| > asynchronously. Therefore, I would like to pause in my synchronous
| > line of code till firstBatchComplete == true.
| >
|
|
Jan 20 '06 #13
Jeez people, I gave the guy a warning about using DoEvents()... It's
nothing more than a quickie, a properly-written application should be
multithreaded/etc... And absolutely polling is a thing of the past.
Sometimes, though, it's not worth the effort. If what you want to do is
simple and the user won't care about some unresponsiveness, then I stand by
my statement, spend 45 seconds writing a polling loop statement rather than
whatever long it takes to do a multi-threaded "proper" app.

I was just giving the guy some choices.

Christoph - I specifically warned against that...
Willy - I never said to use DoEvents() in an alternate thread.
Jon - Your point is well-taken and I agree that proper design is always
better, but sometimes you are in search of a quick solution, for example if
you are quickly writing a data import routine that no end user will ever
see. User inreface responsiveness and saving every clock cycle possible is
not a huge priority. Delivery time might be the big priority (and usually
is).
Jan 20 '06 #14
Gabriel Magaña wrote:
Jeez people, I gave the guy a warning about using DoEvents()...
Where, out of interest? I didn't spot a warning.
It's nothing more than a quickie, a properly-written application should be
multithreaded/etc... And absolutely polling is a thing of the past.
Sometimes, though, it's not worth the effort. If what you want to do is
simple and the user won't care about some unresponsiveness, then I stand by
my statement, spend 45 seconds writing a polling loop statement rather than
whatever long it takes to do a multi-threaded "proper" app.
The trouble is that you spend 45 seconds writing it now - and then
hours later, trying to debug a recursion problem. If the user won't
care about it not being responsive, don't put the call to DoEvents() in
at all. It'll look terrible, but at least you won't have a nasty
threading issue to debug.
I was just giving the guy some choices.

Christoph - I specifically warned against that...
Willy - I never said to use DoEvents() in an alternate thread.
Jon - Your point is well-taken and I agree that proper design is always
better, but sometimes you are in search of a quick solution, for example if
you are quickly writing a data import routine that no end user will ever
see. User inreface responsiveness and saving every clock cycle possible is
not a huge priority. Delivery time might be the big priority (and usually
is).


Delivery time is a priority for me, too. If I'm spending ages
maintaining a previous rushed version which had horrible threading
issues, I can't spend as much time developing new features.

Hacking together poorly designed code never helps in the long run.

It's not a case of trying to save every clock cycle (regulars here will
know I'm not a fan of micro-optimisation). It's a case of trying to do
the Right Thing.

Jon

Jan 20 '06 #15
Jon Skeet [C# MVP] wrote:
Gabriel Magaña wrote:
Jeez people, I gave the guy a warning about using DoEvents()...


Where, out of interest? I didn't spot a warning.


Oh, I see it now - in the follow-up post.

Jon

Jan 20 '06 #16
>> Jeez people, I gave the guy a warning about using DoEvents()...
Where, out of interest? I didn't spot a warning.
I said this:

--- Begin ---
Also, if you do call DoEvents() within your loop do additional
debugging/coding so you don't let the user do something they should not be
doing while you are waiting for the processing to finish, such as pressing a
button again (start the process again for example), close the application,
etc...
--- End ---
The trouble is that you spend 45 seconds writing it now - and then
hours later, trying to debug a recursion problem.
I guess the point did not get across that this is for stuff that end users
will not see. If there is a chance for recursion just disable the button as
part of the click event handler, for example. If the button is disabled,
prevent closing the app via the OnClosing handler of the app. Do proper
exception handling to avoid locking the user into the application. Little
things like that.
If the user won't
care about it not being responsive, don't put the call to DoEvents() in
at all. It'll look terrible, but at least you won't have a nasty
threading issue to debug.
Maybe we do different kinds of projects... I do a lot of database work, and
some import routines will handle as many as 10 million records. I cannot
afford to no update the screen (ie, "processing 2,304 / 10,000") on very
long processes. These are processes one person does every three months for
example, so there is no huge need to make a beautiful interface. Data
integrity is the only concern, do as long as the transactions are handled
correctly no one cares about anything else.
Delivery time is a priority for me, too. If I'm spending ages
maintaining a previous rushed version which had horrible threading
issues, I can't spend as much time developing new features.
The right solution for the right problem is always what should be done. The
OP stated it was some sort of import routine, similar to the kind of stuff I
write sometimes. No, I do not spend hours debugging these routines,
specially not because of threading issues.
Hacking together poorly designed code never helps in the long run.
[...]
It's a case of trying to do the Right Thing.


Agreed, as long as we can also agree that the problem at hand, the user
audience, and the tolerance for different kinds of faults varies depending
on the problem at hand. I would not have advocated single-threaded
operation for something like spell check as you type, for example.
Jan 20 '06 #17
Gabriel Magaña <no*****@no-spam.com> wrote:

<snip>
The trouble is that you spend 45 seconds writing it now - and then
hours later, trying to debug a recursion problem.


I guess the point did not get across that this is for stuff that end users
will not see. If there is a chance for recursion just disable the buttonas
part of the click event handler, for example. If the button is disabled,
prevent closing the app via the OnClosing handler of the app. Do proper
exception handling to avoid locking the user into the application. Little
things like that.


Whether or not end users see bad code, it's still code which can come
and bite you.

Yes, you should learn exception handling etc as well, but I don't think
it's any substitute for writing properly threaded code.
If the user won't
care about it not being responsive, don't put the call to DoEvents() in
at all. It'll look terrible, but at least you won't have a nasty
threading issue to debug.


Maybe we do different kinds of projects... I do a lot of database work, and
some import routines will handle as many as 10 million records. I cannot
afford to no update the screen (ie, "processing 2,304 / 10,000") on very
long processes. These are processes one person does every three months for
example, so there is no huge need to make a beautiful interface. Data
integrity is the only concern, do as long as the transactions are handled
correctly no one cares about anything else.


Except that you've said you *do* care - that you can't afford not to
update the screen.

Either way, I believe that writing code properly saves time in the long
run, with the exception of code which really is "throwaway" code which
will be run a few times and then discarded.
Delivery time is a priority for me, too. If I'm spending ages
maintaining a previous rushed version which had horrible threading
issues, I can't spend as much time developing new features.


The right solution for the right problem is always what should be done. The
OP stated it was some sort of import routine, similar to the kind of stuff I
write sometimes. No, I do not spend hours debugging these routines,
specially not because of threading issues.


Maybe you haven't yet - but if it ever *does* bite you, you'll regret
not doing it properly. It's just like people who say "But I've been
updating controls from other threads for ages, and it's always worked
before..."
Hacking together poorly designed code never helps in the long run.
[...]
It's a case of trying to do the Right Thing.


Agreed, as long as we can also agree that the problem at hand, the user
audience, and the tolerance for different kinds of faults varies depending
on the problem at hand. I would not have advocated single-threaded
operation for something like spell check as you type, for example.


To me, using Application.DoEvents is the wrong thing to do unless
you're solving a problem which just *can't* be solved any other way
(usually due to an inadequacy in a system API). The last time I had to
use it was in a compact framework app ages ago, where I absolutely
*had* to update the UI before I returned from the UI method I was
already in. I can't remember the reasoning, but I felt dirty
afterwards.

I suspect we'll have to agree to disagree.

--
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
Jan 20 '06 #18
>I suspect we'll have to agree to disagree.

Jon, I think we agree a lot, it's just we approached this particular issue
from different perspectives... I understand good programming principles,
and I agree with everything you say about them. I think the only difference
we had was about the benefit vs cost issue which is extremely subjective.

In my situation, though, things move extremely fast, my clients tend to
prefer quick solutions on simple utility-type programs than perfect
solutions which take longer to implement. Between my last message and this
one I've inherited a commercial software product for the residential
mortgage industry. Of course they want many, many updates, and you can bet
I will not be using DoEvents() instead of properly threading the background
file transfers they asked me to implement first! ;-)
Jan 20 '06 #19

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

19 posts views Thread by Tom | last post: by
2 posts views Thread by TJS | last post: by
reply views Thread by the_kiddie98 | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.