Aaa
Aaa

Reputation: 23

beginner trying to implement a timer in a for loop c#

I'm very new to c# and coding in general and am having some problems implementing a timer in a for loop. Basically, the bit of code below is trying to create a number representative of trash output by an island at set intervals, with each output weighted based on island population to be a bit less predictable. it then adds the generated trash figure to a total. The problem I'm having is that the way tutorials use the Timer class means creating an 'Intervaltimer_Elapsed(object sender, ElapsedEventArgs e)' function outside of Main() and I can't work out how to then add whatever is generated by this back to the weights[] array in the Main(). All I really want to do is as soon as the compiler goes into the for loop, tell it to wait 'x' ticks, then continue. Thread.Sleep isn't an option because this is to go in unity, so would interrupt other things. apologies if the code below is a bit gory!

{
class Program
{
    public static double trashperstan8 = 600 * 3.21;
    public static int population = 1000;
    public static double trashperpersperday = 1;
    public static double interval = 60;
    public static double intperday = 1440 / interval;
    public static double trashperint = population * trashperpersperday * (interval / 1440);
    public static int weightnum = population / 200;

    static void Main(string[] args)
    {
        double Trashlevel = new double();
        double stand8sfilled = new double();
        Timer intervaltimer = new Timer((interval / 30) * 1000);
        Console.WriteLine(weightnum);

        for (int inti = 0; inti < intperday; inti++)
        {
            /* at this point, I want to basically tell the code: each time you go 
               through the for loop, wait for x number of ticks then do the method */

            Console.WriteLine(inti);

            double[] weights = new double[weightnum];

            Random rand = new Random();

            for (int i = 0; i < weightnum; i++)
            {
                double weightcontrib = rand.NextDouble();

                weights[i] = weightcontrib;
                Console.WriteLine("{0}: {1}", Array.IndexOf(weights, weightcontrib), weightcontrib);
            }

            double finalweight = 2 * (weights.Sum() / weightnum);
            Console.WriteLine("final weight " + finalweight);

            double weightedtpi = trashperint * finalweight;

            Trashlevel = Trashlevel + weightedtpi;

            stand8sfilled = stand8sfilled + (weightedtpi / trashperstan8);
        }
        Console.WriteLine("trash level " + Trashlevel);
        Console.WriteLine("stand8s filled " + stand8sfilled);
    }

    private static void Intervaltimer_Elapsed(object sender, ElapsedEventArgs e)
    {
    }
}

}

Upvotes: 0

Views: 338

Answers (1)

Eric Lippert
Eric Lippert

Reputation: 659956

All I really want to do is as soon as the compiler goes into the for loop, tell it to wait 'x' ticks, then continue. Thread.Sleep isn't an option because this is to go in unity, so would interrupt other things.

Solution 1: Don't write a loop at all. The timer already is logically a loop.

  • Write a method that is the "body" of the "loop".
  • "Starting the loop" is activating a timer where the body method is the event handler and the timer fires every n milliseconds
  • "Terminating the loop" is deactivating the timer.

Solution 2: Write a loop, don't use a timer.

Make the method async and then await Task.Delay(whatever); to asynchronously wait for your delay. Your method will suspend when it hits the await, and resume at some point after the delay task is complete.

The latter is probably the better solution in that the code more closely resembles your description of it.

I don't know enough about Unity to say which is the better solution in their framework.

Upvotes: 4

Related Questions