Simple program logic to Call method continuously - logic

I am in a situation, in which my program needs to do processing and then wait for some interval, let's say 5 seconds and the do the same processing again.
I don't know how to implement the logic.
I have developed a logic, the code is below:
private void ProcessEmail()
{
PprocessEmail:;
//Do whatever you want
System.Threading.Thread.Sleep(5000);
goto ProcessEmail;
}
What this code does:
I only have to call this method once, it will do the processing then wait for 5 seconds and then again process.
So far above code is working fine, but i have heard using "goto" statements is not considered good in programming.
I want to know, will there be any side effect of this code or is there any other efficient way of doing the same thing.

Look at loops. This Wiki article might be a good place to start for the theory.
If it's C#, what you'd use is a while(true) that would loop forever.

Related

How to get the best perfomance in Google Script?

As you might know, Google gives only 1 hour of execution time for triggered scripts (web-apps and manual calls are not in this hour).
I hadn't found a good explanation of how to boost script perfomance, so I had to find out it myself. Here's what helped me:
10 tips & tricks to get the best perfomance in Google Script
There is an official Google's best practices documentation on how to write scripts. However it's not that comprehensive and misses some important tips and explanations, which you will additionally find here.
Use as less as possible time consuming methods.
Any method which is considered as time-consuming by Google you will always find in the execution report .
Some examples of time-consuming methods:
Methods, which read/save information to the Sheet: getValue, getValues, getDisplayValue, getRangeByName, getSheet, setValue, deleteRow etc. Some consume more, some less.
Methods, using other external services, like GmailApp, Utilities etc.
Document/Script properties (but they are a somewhat faster than getting data from sheet).
If you use Libraries, don't forget to create a new version of the library, when you finish coding, and switch off developer mode in you calling scripts (sorry for non-English screenshots). In my case it speeded up the dummy script launches (when the script got a signal, that it should stop) by 3 times.
The parts of code, which are non included into any function, and can be executed conditionally must be grouped into initialization functions and called when a condition is met. This actually can be applied to any part of code. The thing is that the code, which is located outside of any function, is always executed, whether it's in your basic project or in a library.
Use Batch operations when possible. One getValues() on 100 cells is much faster then 100 getValue() on each cell. Same for deleteRows() and setValues() etc.
If you use many script/document properties, use batch methods also.
If you use many static Named Ranges, create a cache for all of them and make an object (hash array) from that. Make a refreshing procedure and use it when required. My project has 137 named ranges: this point had a huge effect.
Avoid sleep method, if possible.
Google advises to use cache for web pages with fetchUrl (if applicable).
Google advises to avoid Library usage in UI heavy scripts (e.g. when you use triggers based on Google Sheet actions).
If your triggered script isn't supposed to work 24 hours make a work schedule for it and route your script to a lightweight procedure.
Example:
if ((new Date()).getHours() < 9) {
var TriggeredEveryMinuteFunction = function() {
//...do some lightweight stuff or nothing...
}
} else {
function TriggeredEveryMinuteFunction() {
// ...do some heavy stuff...
func2();
}
function func2() { /*some more stuff*/ }
var func3 = function() { /*some more stuff*/ }
var etc() { /*some more stuff*/ }
}
In this example functions func2,func3,etc are not compiled when it's less than 9 o'clock.
If you try to call them, you'll get "not found" message.

How do I do a For loop without freezing the GUI?

I would like to know how I could run the following loop in a way where it doesn't freeze the GUI, as the loop can take minutes to complete. Thank you.
For i = 0 To imageCount
'code
Next
The short answer is you run the loop on another thread. The long answer is a whole book and a couple of semesters at university, because it entails resource access conflicts and various ways of addressing them such as locking and queueing.
Since you appear to be using VB.NET I suggest you use the latest version of the .NET framework and take advantage of Async and Await, which you can learn about from MSDN.
These keywords implement a very sophisticated canned solution that will allow you to achieve your goals in blissful ignorance of the nightmare behind them :)
Why experienced parallel coders would bother with async/await
Standout features of async/await are
automatic temporary marshalling back to the UI thread as required
scope of exception handlers (try/catch/finally) can span both setup and callback code
you write what is conceptually linear code with blocking calls on the UI thread, but because you declare calls that block using "await", the compiler rewrites your code as a state machine makes the preceding points true
Linear code with blocking calls is easy to write and easy to read. So it's much better from a maintenance perspective. But it provides an atrocious UX. Async/await means you can have it both ways.
All this is built on TPL; in a quite real sense it's nothing more than a compiler supported design pattern for TPL, which is why methods tagged as async are required to return a Task<>. There's so much to love about this, and no technical downside that I've seen.
My only concern is that it's all too good, so a whole generation will have no idea how tall the giants on whose shoulders they perch, just as most modern programmers have only dim awareness of the mechanics of stack frames in call stacks (the magic behind local variables).
You can run the loop on a separate thread. Read about using BackgroundWorker here http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx

Biggest beef with game loops

What do you hate most about the modern game loop? Can the game loop be improved or is there just a better alternative, such as an event-driven architecture?
It seems like this really ought to be a CW...
I'm taking a grad-level game engine programming course right now and they're sticking with the game loop approach. Granted, that doesn't mean it's the only/best solution but it's certainly logical. Using a loop allows you to ensure that all game systems get their turn to run without requesting their own timed interrupts or something else. Control can be centralized: in my current project, I have a GameManager class that, each frame, loops through the Update(float deltaTime) function for every registered object in turn. I don't have to debug an event system or set up timed signals, I just use a loop to call a series of functions. No muss, no fuss.
To answer your question of what do I hate most, the loop approach does logically lend itself to liberal use of inheritance and polymorphism which can bloat the size/complexity of your objects. If you're not careful, this can be a mild-to-horrible pitfall. If you are careful, it may not be a problem at all.
No matter there is any event in the game or not, game is supposed to draw itself and update it at a fixed rate, so I don't think dropping the game loop is possible. Still I would be wondered if anyone can think of any other alternative of game loop.
Usually the event driven architectures work best for games (only do something if the user wants something done). BUT, you'll still always need to have a thread constantly redrawing the world.
To be fully event based you could spawn an extra thread that does nothing but put a CPUTick event into your event queue every x milliseconds.
In JavaScript this is usually the more natural route, because you can so easily create an extra 'thread' that sends you the events with setInterval().
Or, if you already have a loop in the framework containing your game - like JS has in the browser, or python has with twisted - you can tell that looper to call you back at fixed intervals. e.g.:
function gameLoop() {
// update, draw...
}
window.setInterval(gameLoop, 1000/fps);

Differences between Coroutines and `goto`?

I always read about the horrible thing that "goto" is. But today, reading about the Google programming language Go, I see that it suports Coroutines (Goroutines).
The question is:
Coroutine == GoTo
Or
Coroutine != GoTo?
Why?
Goroutines are not the same as a goto - they run in parallel with the main code. When you state something like (from their example at http://golang.org/doc/effective_go.html)
go list.Sort(); // run list.Sort in parallel; don't wait for it.
the mainline code continues on - it doesn't wait for the sort to finish. The sort routine starts up on its own lightweight thread of execution and when it finishes the sort that thread exits.
A goto would cause the mainline code to branch to a separate execution path - so the statements after the goto would never get run.
The key difference is that goto statements in languages that support them allow jumping to any location in the program with little or no restriction. While coroutines may on the surface seem similar they are very different.
Coroutines allow procedures to be suspended (with all their context) and resumed at certain locations. So while coroutines do pause and yield control to other procedures before they complete and then resume later, the points at which the procedures yield and resume from is known ahead of time.
It is not possible to simply jump to an arbitrary line in a procedure, the procedure in question has to waiting to be resumed at a specific location. While this passing of control is much more structured than with goto it is possible to write confusing code by overusing this powerful mechanism. Then again that is that not the case with every powerful programming language feature? ;-)

Best refactoring for the dreaded While (True) loop

If, like me, you shiver at the site of a While (True) loop, then you too must have thought long and hard about the best way to refactor it away. I've seen several different implementations, none really better than any other, such as the timer & delegate combination.
So what's the best way you've come up with or seen to refactor the dreaded While (True) loop?
Edit: As some comments mentioned, my intent was for this question to be an "infinite loop" refactoring, such as running a Windows style service where the only stop conditions would be OnStop or a fatal exception.
My preference would be
start:
// code goes here
goto start;
This most clearly expresses the intent. Good luck getting it past your coding standards. (Wonder how much karma this is going to cost me).
Do we really need to refactor while(true) loops?
Sometimes it's a coding standard and most of the developers has got used to this structure. If you have to think hard on how to refactor this code, are you sure it's a good idea to refactor it?
Goto used to be a black sheep in coding standards. I've met algorithms where goto made the code much more readable and shorter. Sometimes it doesn't worth to refactor (or better to use goto).
On the other hand you can avoid while(true) most of the time.
What's so dreaded about it? Try finding a common break condition and refactor it to be the head of the loop. If that's not possible – fine.
When I encounter a while(true) loop, that tells me either
the break condition is not easily tested at the top (or bottom) of the loop,
there are multiple break conditions,
or the prior programmer was too lazy to factor the loop properly.
1 and 2 means you might as well stick with while(true). (I use for(;;), but that's a style thing in my opinion.) I'm with another poster, why dread this? I dread tortored loops that jump through hoops to get the loop rolled "properly".
Why refactor? And what is so "dreadful" about this construct? It is widely used, and well understood.
If it ain't broke, don't fix it.
Replace True with the condition you were going to use to break out of the loop.
In the case of a service or background thread, you might use:
volatile bool m_shutdown = false;
void Run()
{
while (!m_shutdown)
{ ... }
}
The "running forever" situation is sometimes part of a larger state machine. Many embedded devices (with run-forever loops) don't really run forever. They often have several operating modes and will sequence among those modes.
When we built heat-pump controllers, there was a power-on-self-test (POST) mode that ran for a little while. Then there was a preliminary environmental gathering mode that ran until we figured out all the zones and thermostats and what-not.
Some engineers claimed that what came next was the "run-forever" loop. It wasn't really that simple. It was actually several operating modes that flipped and flopped. There was heating, and defrosting, and cooling, and idling, and other stuff.
My preference is to treat a "forever" loop as really just one operating mode -- there may be others at some point in the future.
someMode= True
while someMode:
try:
... do stuff ...
except SomeException, e:
log.exception( e )
# will keep running
except OtherException, e:
log.info( "stopping now" )
someMode= False
Under some circumstances, nothing we've seen so far sets someMode to False. But I like to pretend that there'll be a mode change in some future version.
#define ever 1
for (;ever;)
?
Meh, just leave it how it is, while (true) is probably as legible as you're going to get..
errr, to be a refactoring.....
Replace Infinite Loop with Infinite Recursion :-)
well, if you have a language that supports Tail calls....
If you want it to continue indefinitely until a total abortion of program flow, I don't see anything wrong with while (true). I encountered it recently in a .NET data collection service that combined while (true) with thread.sleep to wake up every minute and poll the third-party data service for new reports. I considered refactoring it with a timer and a delegate, but ultimately decided that this was the simplest and easiest-to-read method. 9 times out of 10 it's a clear code smell, but when there's no exit condition, why make things more difficult?
I don't mind it when the infinite loop is contained within a window, and dies with the window.
Think of the Hasselhoff Recursion.
void whiletrue_sim(void)
{
//some code
whiletrue_sim();
}
Warning: Your stack may overflow.

Resources