83904

Timer is not working in separate class in C#

I would like to get the time my user instance is alive. Therefore I added the following timer function. But it does not work nevermind what I try:

using System; using System.Collections.Generic; using System.Timers; using System.Threading; using System.Windows; public MainWindow() { User myUser = new User(); System.Timers.Timer timer = new System.Timers.Timer(1000); timer.Elapsed += new ElapsedEventHandler(OnTimerElapsed); timer.AutoReset = true; timer.Enabled = true; myUser.setTimer(timer); } private void OnTimerElapsed(object source, ElapsedEventArgs e) { User currentUser = (User)source; MessageBox.Show("OnTimerElapsed: " + currentUser.Id); }

This is my UserClass which includes the timer instance:

public class User : NotifyPropertyChanged { private System.Timers.Timer _timer; public void setTimer(System.Timers.Timer timer) { _timer = timer; } }

Answer1:

A Timer is good for causing actions to happen after some interval, or on a periodic basis. But a Timer does not in and of itself actually keep track of time. You need a Stopwatch for that.

Something that might work in your example:

class User { private Stopwatch _alive = Stopwatch.StartNew(); public TimeSpan Alive { get { return _alive.Elapsed; } } }

This adds a Stopwatch to your User object so that it knows how long it's been alive.

Then in your window code:

public MainWindow() { User myUser = new User(); myUser.Timer = new System.Timers.Timer(1000); myUser.Timer.Elapsed += (sender, e) => OnTimerElapsed(myUser); myUser.Timer.AutoReset = true; myUser.Timer.Enabled = true; } private void OnTimerElapsed(User currentUser) { MessageBox.Show(string.Format("OnTimerElapsed: {0}, alive {1:0} seconds", currentUser.Id, currentUser.Alive.TotalSeconds)); }

This does a couple of things:

    <li>It changes the timer handler so that it captures and passes the myUser object reference to the actual handler method. In your example, you were trying to cast the source parameter, but that's the Timer object, not a User object.</li> <li>It retrieves the TimeSpan value from the Alive property, and displays the value as seconds.</li> </ul>

    Note that the User object does not itself need to know anything about the Timer object, at least not to accomplish the above.

    Something like that should work; obviously you will make modifications according to your specific need.

    Answer2:

    You are trying to cast the object source in the OnTimerElapsed to a type User

    It's a Timer type.

    You are causing an System.InvalidCastException every time the Timer ticks. It's not crashing, because it's on a worker thread.

    By the way, simply setting a breakpoint on the line

    User currentUser = (User)source;

    would have revealed this error.

    The handler method's first parameter is always the object that fired the event, in this case, it's the Timer instance, not the User type defined by you.

Recommend

  • Multiple timer elapsed issue
  • How to deal with “runtime error 50290” when using SetTimer API?
  • How are signals handled in Unix?
  • How to fix a cross-thread exception in C#? [duplicate]
  • Modify response from Django REST API using CustomUserModel extending default User Model and API clas
  • ffmpeg concat error-unusual video
  • Xamarin ContentView/View Lifecycle
  • Background Geolocation ServiceWorker - onMessage Event order when Web App regains focus [closed]
  • How to add fields in extended UserAdmin
  • FOREIGN KEY constraint failed in django admin panel when creating/editing/deleting a user. (Using cu
  • Should I call base.OnAuthorization(filterContext)?
  • POSIX TIMER- Have multiple timers
  • Parse weird bug in Swift that causes ACL write permissions to change to an objectId
  • System.Timers.Timer (.NET) really slow?
  • Context is null in SignalR hub
  • How do I extend UserCreationForm to include email field
  • How to solve the jshint error `Don't make functions within a loop.` with jquery $.grep
  • For Each Loop through DataGridViewColumn Headers
  • adding item to window Extjs 4
  • TypeError: Main.login is not a function
  • Basler USB Camera byte buffer to image conversion
  • How can I mock ui-router's resolve values when testing a state's configuration?
  • Why is the size of this struct 32?
  • Controls, properties, events and timers running in design time
  • output of program is not same as passed argument
  • javascript inside java/jsp code
  • Sending data from AppleScript to FileMaker records
  • Javascript + PHP Encryption with pidCrypt
  • jquery mobile loadPage not working
  • How to delete a row from a dynamic generate table using jquery?
  • json Serialization in asp
  • KeystoneJS: Relationships in Admin UI not updating
  • AngularJs get employee from factory
  • Rails 2: use form_for to build a form covering multiple objects of the same class
  • Load html files in TinyMce
  • Getting Messege Twice Using IMvxMessenger
  • How to stop GridView from loading again when I press back button?
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • How can i traverse a binary tree from right to left in java?
  • How can I use threading to 'tick' a timer to be accessed by other threads?