Search code examples
c#taskfactory

How do I run a method while a timer is running on screen?


First off- this is a homework assignment. I'm supposed to go beyond what we have learned, so I thought of a WPM console application. I did a lot of searching on Timers, but that's way too over my head for first semester. So I found an easier way. The thing is, I want to be able to call some string and have the user type them in, and run a calculation in the end to determine their words per minute. I read that using Task.Factory.StartNew should let me run two methods.

class Program
{
    static void Main( string[] args )
    {
        Timer go = new Timer( );
        WordBank display = new WordBank( );

        Task.Factory.StartNew(go.timer1_Tick);
        Task.Factory.StartNew(display.LevelOneWords);
        Console.ReadKey( );

    }
}//end main

class Timer
{
public Timer()
{}
    public void timer1_Tick(  )
    {
        int seconds= 0;
        DateTime dt = new DateTime( );

        do
        {
            Console.Write("One minute timer: " + dt.AddSeconds(seconds).ToString("ss"));
            Console.Write("\r");
            seconds++;
            Thread.Sleep(1000);                
        } while ( seconds< 60 );
    }
}//end Timer

class WordBank
{
public WordBank()
{ }

public void LevelOneWords()
{
        string easyWords = "the boy had so much fun at the park.";
        Console.WriteLine("\n\n", easyWords);
        Console.ReadKey( );
}

When I run the program the timer starts for a second and then is immediately replaced with the string. Am I using Task.Factory.StartNew incorrectly?


Solution

  • Instead of running a timer while they are typing (requiring two programs simultaneously), instead try getting the time when they initially start typing, the time when they end typing, and then do some division. IE:

    static void Main()
    {
        // Displays WordBank
        WordBank display = new WordBank();
    
        var startTime = DateTime.Now;
    
        // Let them type for X amount of time
        var totalWords = TakeUserInputForXSeconds(45);
    
        var endTime = DateTime.Now;
    
        var wpm = totalWords / (endTime.Subtract(startTime).TotalMinutes);
    }
    

    For the TakeUserInputForXSeconds method, I would look at the information in this post: Stop running the code after 15 seconds