473,664 Members | 2,967 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C# Command to Wait a Specified Period of Time

What is the C# command to wait for a specified period of time?

I am writing a windows service that will process a file once it has beed
created or changed. I'm using the fileSystemWatch er to detect when a
specific file has been created or changed. That works fine to a point. The
event does fire when the file is being created or changed but I then blow up
when I attempt to open the file because the creation or changing has not
finished.

Using the try/catch structure, I am wanting to attempt to open the file. If
it is still being used, then wait a minute and try again. I rather use a
command (assuming that one exists) to sit there for say a minute and try
again.

Using a timer evolves a callback. I was hoping for a simple solution.
Jan 15 '08 #1
40 29333
"Robert E. Flaherty" <Ro************ *@discussions.m icrosoft.comwro te in
message news:C9******** *************** ***********@mic rosoft.com...
What is the C# command to wait for a specified period of time?

I am writing a windows service that will process a file once it has beed
created or changed. I'm using the fileSystemWatch er to detect when a
specific file has been created or changed. That works fine to a point.
The
event does fire when the file is being created or changed but I then blow
up
when I attempt to open the file because the creation or changing has not
finished.

Using the try/catch structure, I am wanting to attempt to open the file.
If
it is still being used, then wait a minute and try again. I rather use a
command (assuming that one exists) to sit there for say a minute and try
again.

Using a timer evolves a callback. I was hoping for a simple solution.
Something like this will work. You can't sleep for 60 seconds because your
service won't stop for 60 seconds if someone pushes stop.

for(int i = 0; i < 60; i++)
{
System.Threadin g.Thread.Sleep( 1000);
if(StoppHasBinP ushed) break;
}


Jan 15 '08 #2
On Mon, 14 Jan 2008 16:21:01 -0800, Robert E. Flaherty
<Ro************ *@discussions.m icrosoft.comwro te:
[...]
Using the try/catch structure, I am wanting to attempt to open the
file. If
it is still being used, then wait a minute and try again. I rather use a
command (assuming that one exists) to sit there for say a minute and try
again.

Using a timer evolves a callback. I was hoping for a simple solution.
What's not simple about using a timer?

Timer timer = new System.Windows. Forms.Timer();

timer.Interval = 60000;
timer.Tick += delegate
{
if (!fRetry || TryOpenFile())
{
timer.Stop();
}
};
timer.Start();

Where the method "TryOpenFil e()" contains your logic to attempt the
operation with a try/catch exception handler, returning "true" on success,
"false" on failure. The "fRetry" flag is provided for convenience, to
support canceling as suggested by Michael. Declare it somewhere else,
initialize to "false", set it to true if you want to cancel the operation
before it's completed.

Alternatively, you could just store a reference to the timer elsewhere and
stop the timer explicitly when the operation needs to be canceled.

I don't see the point in code like Michael's. Just as it doesn't make
sense to block for 60 seconds, preventing the user from canceling the
operation until then, it also doesn't make sense to block for 1 second,
preventing the user from canceling the operation until then. You
shouldn't block at all. Just set up a timer, try the operation on every
tick, and once it succeeds, stop the timer.

It's really not that complicated. The number of lines of code is about
the same as Michael's proposal, and this implementation has the added
benefit of not doing something bad like blocking the GUI thread for
extended periods of time.

You could, of course, put the operation on a whole new thread and let it
sit and wait there. Then you could just call Sleep(60000) and perform
whatever logic, including checking for a successful file open as well as
having the operation canceled, in a loop there:

while (!fRetry)
{
if (TryOpenFile())
{
break;
}
Thread.Sleep(60 000);
}

But then you need to put that code in a thread somewhere, as well as deal
with any cross-thread issues. I'd hardly say that's simpler solution than
using a timer.

Pete
Jan 15 '08 #3
"Peter Duniho" <Np*********@nn owslpianmk.comw rote in message
news:op******** *******@petes-computer.local. ..
I don't see the point in code like Michael's. Just as it doesn't make
sense to block for 60 seconds, preventing the user from canceling the
operation until then, it also doesn't make sense to block for 1 second,
preventing the user from canceling the operation until then. You
shouldn't block at all. Just set up a timer, try the operation on every
tick, and once it succeeds, stop the timer.

Doesn't this apply equally to all code that blocks then? Most database
lookups of any complexity will block for 1 second. In this situation we can
just reduce the interval to 1/10th. While your code is a similar number of
lines it is more complex. I can't say I'm a big fan of those inline
delegates.
Jan 15 '08 #4
On Mon, 14 Jan 2008 18:23:52 -0800, Michael C <mi**@nospam.co mwrote:
Doesn't this apply equally to all code that blocks then? Most database
lookups of any complexity will block for 1 second. In this situation we
can
just reduce the interval to 1/10th. While your code is a similar number
of
lines it is more complex. I can't say I'm a big fan of those inline
delegates.
Why not? They work quite well, especially when you take advantage of the
variable-capturing they provide. They can greatly simplify your code, and
IMHO this is a good example of them doing just that. An implementation
not using an anonymous method would require at least twice as much
effort. Not that the effort would be great in either case, but the
alternative is less readable as well.

I would also disagree that my code is "more complex". It only appears
that way because you left out at least a couple of statements that are
required: the line that actually attempts to do the file open, and the
line that (ick!) calls DoEvents() so that you can respond to user input.

I personally find my code _simpler_, not more complex. It's not
re-entrant and it doesn't cause the thread to get stuck in the Form's
event-handling procedure for extended periods of time.

In any case, yes..."this" does apply equally to all code that blocks.
IMHO, it's not a good idea to put blocking code in the GUI thread. For
some "quick and dirty" or extremely simple applications it might be okay,
but it's not something that should show up in anything serious, and this
is especially true when the blocking could be significantly long.

Pete
Jan 15 '08 #5
while(true)
{
try
{
TryOpenFile(e.N ame);
ProcessFile(e.N ame);
break;
}
catch(Exception ex)
{
System.Threadin g.Thread.Sleep( 1000);
continue;
}
}

--
Misbah Arefin

"Robert E. Flaherty" wrote:
What is the C# command to wait for a specified period of time?

I am writing a windows service that will process a file once it has beed
created or changed. I'm using the fileSystemWatch er to detect when a
specific file has been created or changed. That works fine to a point. The
event does fire when the file is being created or changed but I then blow up
when I attempt to open the file because the creation or changing has not
finished.

Using the try/catch structure, I am wanting to attempt to open the file. If
it is still being used, then wait a minute and try again. I rather use a
command (assuming that one exists) to sit there for say a minute and try
again.

Using a timer evolves a callback. I was hoping for a simple solution.
Jan 15 '08 #6
"Michael C" <mi**@nospam.co mwrote in message
news:Oz******** ********@TK2MSF TNGP03.phx.gbl. ..
IMO it's not MUCH better to have the code in a seperate function. In your
example we actually exit the function but jump back into it right in the
middle!! Yuk!
That should read "it's much better" :-)

Michael
Jan 16 '08 #7
On Tue, 15 Jan 2008 18:03:07 -0800, Michael C <mi**@nospam.co mwrote:
IMO it's not MUCH better to have the code in a seperate function. In your
example we actually exit the function but jump back into it right in the
middle!! Yuk!
The anonymous method is not part of the method in which it's declared.
It's a complete method unto itself. The execution of the anonymous method
does not "jump back into" the method in which it's declared.

Perhaps the reason you don't like anonymous methods is that you have
failed to conceptualize them in a useful way. It's true that when you
don't understand something, it seems a lot less useful than when you do.
>And you call DoEvents(), which hides a remarkable degree of complexity
(such as the re-entrant behavior I mentioned).

Naturally either solution is potentially re-entrant.
Negative. An anonymous method doesn't have any of the re-entrancy issues
that calling DoEvents() does.
>I'm not saying it does. I'm saying you glossed over the complexity in
your own suggestion.

Having a message queue is part of any windows app.
Having a _synchronous_ message queue is a normal part of any Windows
application.
Allowing that to process is minor.
"Minor" is in the eye of the beholder. Suffice to say, I disagree with
the claim that completely changing the messaging architecture of an
application is a "minor" alteration.

Pete
Jan 16 '08 #8
"Peter Duniho" <Np*********@nn owslpianmk.comw rote in message
news:op******** *******@petes-computer.local. ..
The anonymous method is not part of the method in which it's declared.
It's a complete method unto itself. The execution of the anonymous method
does not "jump back into" the method in which it's declared.

Perhaps the reason you don't like anonymous methods is that you have
failed to conceptualize them in a useful way. It's true that when you
don't understand something, it seems a lot less useful than when you do.
Granted I don't understand what's going on under the hood but that is part
of the problem. As I said previously it must compile to a seperate function
but contains another functions local variables. I say again Yuk!
Negative. An anonymous method doesn't have any of the re-entrancy issues
that calling DoEvents() does.
I don't see how you can say that. The only way mine can be re-entrant is if
the user clicks the GO button again. Yours suffers the same problem as far
as I can see as someone can kick off the entire process again if they like.
"Minor" is in the eye of the beholder. Suffice to say, I disagree with
the claim that completely changing the messaging architecture of an
application is a "minor" alteration.
From the programmers pov doevents is quite simple. While your method isn't
much more complicated it still is.

BTW, who said anything about DoEvents. It was you who added the idea of
using DoEvents. And who said anything about a GUI, this is a windows
service.

Michael
Jan 16 '08 #9
On Tue, 15 Jan 2008 19:07:20 -0800, Michael C <mi**@nospam.co mwrote:
Granted I don't understand what's going on under the hood but that is
part
of the problem.
IMHO, it's poor practice to denigrate a language feature if you don't
fully understand it.
As I said previously it must compile to a seperate function
but contains another functions local variables. I say again Yuk!
And I say "Aha!" Variable capturing is one of the things that makes
anonymous methods so useful.
>Negative. An anonymous method doesn't have any of the re-entrancy
issues
that calling DoEvents() does.

I don't see how you can say that. The only way mine can be re-entrant is
if
the user clicks the GO button again.
Actually, it's re-entrant the moment you call DoEvents(). "Under the
hood", you've got a window's "window proc" (aka "wndproc") that is busy
handling a specific window message, having been called from a message pump
loop. When you call DoEvents(), that enters an entirely new message pump
loop, which will in turn call the window proc again.

Just because you don't see the re-entrancy, that doesn't mean it doesn't
exist, nor does it mean there's no potential for a problem. The user
clicking the same button again isn't the issue, and in fact I would expect
that a proper program would disable the button if it's inappropriate for
it to be clicked. It's the question of the fact that your window hasn't
finished handling one window message, and now may be asked to process any
number of new window messages.

It's an intractable design problem inherent in calling DoEvents(). It
leads to code that is at best difficult to maintain, and at worst can
contain subtle bugs that are difficult to find, never mind solve.
Yours suffers the same problem as far
as I can see as someone can kick off the entire process again if they
like.
Mine ensures that the Form class is handling one message at a time. You
can always _add_ re-entrancy to the code, but it's not inherent in the
anonymous method technique, while it is inherent in using DoEvents().
From the programmers pov doevents is quite simple. While your method
isn't
much more complicated it still is.
DoEvents() only _seems_ to be simple. The fact that you believe it
actually _is_ simple is a symptom of the basic problem. DoEvents() has
fooled you into thinking that it's simple, when in fact it's actually
quite a complicated addition to the architecture.
BTW, who said anything about DoEvents. It was you who added the idea of
using DoEvents. And who said anything about a GUI, this is a windows
service.
I can only laugh at this point. It appears that I missed an important
aspect of the original question (it's a service), and you missed an
important aspect of my reply: I used the System.Windows. Forms.Timer class
in a context where that class isn't useful or desirable at all.

That said, consider "GUI" as a general talking point if you will. The
issue here is whether the thread is available to process other activity.
You wrote "You can't sleep for 60 seconds because your service won't stop
for 60 seconds if someone pushes stop", so obviously you anticipate doing
_something_ inside that loop that allows the service to process other
input.

Whether that something is DoEvents() or something else, the same basic
issues apply though I agree that some specifics that apply to DoEvents()
obviously wouldn't in other implementations . In particular, there are
still re-entrancy issues and depending on the architecture of the service
they could be even more complex than those introduced by the use of
DoEvents() in a Forms application.

Now, in the context of a service, timers get more complicated than when
using System.Windows. Forms.Timer in a Forms application. All of what I
wrote was aimed specifically at a Forms application, and that's where the
System.Windows. Forms.Timer class is especially helpful. It ensures that
execution of the timer event handler is synchronized with other activity
in the GUI thread. Obviously that benefit doesn't apply when using some
other timer mechanism.

Because of that, in this situation my recommendation would be to run the
"retry" logic on a different thread, per my alternate suggestion in my
original reply.

There is still no need, nor is it desirable, to have any thread wait 60
seconds by actually waiting for 1 second 60 times. Just make the thread
wait 60 seconds and be done with it. If the process needs to be available
to do other work, handle that other work in a different thread.

Pete
Jan 16 '08 #10

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

Similar topics

0
2256
by: Jim Mitchell | last post by:
I have the code snippet below. I fill a table of imagebuttons and would like to know which one was clicked to trigger the post back. Unfortunately, the Command event does not fire unless I load the images on the load_page event. Since I want to load the table of images based on the click event from another control, and only based on feedback from some controls do I even display the image list, I thought I could trap the command or click...
2
1564
by: vijayasb | last post by:
Hi, I have a requirement to calculate or get process wait time and process ready time.By using GetProcessTimes API we can get user time, kernel time , creation time and exit time of a process. Using kernel and user time we can calculate CPU usage of a process. I need information to calculate or retrieve wait and ready time of a process.Please help me in getting this info.I need it very urgently. Thanks, Viju
1
8549
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8636
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7375
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6187
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5660
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4351
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2764
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2003
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1759
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.