我想这可能会被标记为重复和关闭,但我无法找到一个清晰、简洁的答案来回答这个问题。所有的回复和资源几乎都涉及Windows Forms和利用预构建的实用类,如BackgroundWorker。我非常希望能够理解这个概念的核心,以便将基本知识应用于其他线程实现。
我想要实现的一个简单例子:
//timer running on a seperate thread and raising events at set intervals
//incomplete, but functional, except for the cross-thread event raising
class Timer
{
//how often the Alarm event is raised
float _alarmInterval;
//stopwatch to keep time
Stopwatch _stopwatch;
//this Thread used to repeatedly check for events to raise
Thread _timerThread;
//used to pause the timer
bool _paused;
//used to determine Alarm event raises
float _timeOfLastAlarm = 0;
//this is the event I want to raise on the Main Thread
public event EventHandler Alarm;
//Constructor
public Timer(float alarmInterval)
{
_alarmInterval = alarmInterval;
_stopwatch = new Stopwatch();
_timerThread = new Thread(new ThreadStart(Initiate));
}
//toggles the Timer
//do I need to marshall this data back and forth as well? or is the
//_paused boolean in a shared data pool that both threads can access?
public void Pause()
{
_paused = (!_paused);
}
//little Helper to start the Stopwatch and loop over the Main method
void Initiate()
{
_stopwatch.Start();
while (true) Main();
}
//checks for Alarm events
void Main()
{
if (_paused && _stopwatch.IsRunning) _stopwatch.Stop();
if (!_paused && !_stopwatch.IsRunning) _stopwatch.Start();
if (_stopwatch.Elapsed.TotalSeconds > _timeOfLastAlarm)
{
_timeOfLastAlarm = _stopwatch.Elapsed.Seconds;
RaiseAlarm();
}
}
}
两个问题:首先,我该如何将事件传递到主线程以便通知感兴趣的方Alarm件。
其次,关于Pause()方法,它将被在主线程上运行的对象调用;我能否通过调用_start()/_stop()直接操作在后台线程上创建的Stopwatch?如果不能,主线程是否可以像上面所示那样调整_paused布尔值,以便后台线程可以看到_paused的新值并使用它?
我发誓,我已经做过我的研究,但这些(基本和关键)细节对我来说还不清楚。
免责声明:我知道有一些类可用,它们提供了我正在描述的Timer类的确切特定功能。 (事实上,我相信这个类就叫做Threading.Timer)然而,我的问题并不是为了帮助我实现Timer类本身,而是理解如何执行驱动它的概念。