计时器不在 C# 中的单独类中工作 [英] 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);
}
这是我的 UserClass,其中包括计时器实例:
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;
}
}
推荐答案
Timer
有助于在某个时间间隔后或定期发生动作.但是 Timer
本身实际上并没有跟踪时间.为此,您需要一个 秒表
.
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; } }
}
这会向您的 User
对象添加一个 Stopwatch
,以便它知道自己存活了多长时间.
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));
}
这做了几件事:
- 它更改了计时器处理程序,以便它捕获并将
myUser
对象引用传递给实际的处理程序方法.在您的示例中,您试图强制转换source
参数,但这是Timer
对象,而不是User
对象. - 它从
Alive
属性中检索TimeSpan
值,并将该值显示为秒.
- 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 thesource
parameter, but that's theTimer
object, not aUser
object. - It retrieves the
TimeSpan
value from theAlive
property, and displays the value as seconds.
请注意,User
对象本身不需要知道关于 Timer
对象的任何信息,至少不需要完成上述操作.
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.
这篇关于计时器不在 C# 中的单独类中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!