problems getting a timer to work
-
I am having problems getting a simple timer to work. I am very new to C#. When I go to compile the code below I get the following error: An object reference is required for the nonstatic field, method, or property 'TimerTest.mStartTime' Anyone got any ideas ? using System; using System.IO; using System.Timers; class TimerTest { public DateTime mStartTime; public static void Main() { Timer tmr = new Timer(); tmr.Tick += new EventHandler(OnTimedEvent); tmr.Interval= 1000; DateTime mStartTime = DateTime.Now; Console.WriteLine("Timer test running..."); tmr.Enabled = true; while(true) { } } public static void OnTimedEvent(object source, EventArgs e) { String timestring; DateTime now = DateTime.Now; TimeSpan diff = now.Subtract(mStartTime); timestring = (diff.Hours.ToString("d2" + ":" + diff.Minutes.ToString("d2") + ":" + diff.Seconds.ToString("d2")); Console.WriteLine("{0}",timestring); } }
-
I am having problems getting a simple timer to work. I am very new to C#. When I go to compile the code below I get the following error: An object reference is required for the nonstatic field, method, or property 'TimerTest.mStartTime' Anyone got any ideas ? using System; using System.IO; using System.Timers; class TimerTest { public DateTime mStartTime; public static void Main() { Timer tmr = new Timer(); tmr.Tick += new EventHandler(OnTimedEvent); tmr.Interval= 1000; DateTime mStartTime = DateTime.Now; Console.WriteLine("Timer test running..."); tmr.Enabled = true; while(true) { } } public static void OnTimedEvent(object source, EventArgs e) { String timestring; DateTime now = DateTime.Now; TimeSpan diff = now.Subtract(mStartTime); timestring = (diff.Hours.ToString("d2" + ":" + diff.Minutes.ToString("d2") + ":" + diff.Seconds.ToString("d2")); Console.WriteLine("{0}",timestring); } }
B. Wood wrote: public DateTime mStartTime; public static DateTime mStartTime; :) Since your methods are static, the data it accesses must be static, or have a reference to an instance of the class. James Sonork ID: 100.11138 - Hasaki "Not be to confused with 'The VD Project'. Which would be a very bad pr0n flick. :-D" - Michael P Butler Jan. 18, 2002
-
B. Wood wrote: public DateTime mStartTime; public static DateTime mStartTime; :) Since your methods are static, the data it accesses must be static, or have a reference to an instance of the class. James Sonork ID: 100.11138 - Hasaki "Not be to confused with 'The VD Project'. Which would be a very bad pr0n flick. :-D" - Michael P Butler Jan. 18, 2002