我试图在不使用计时器时停止它,并在需要时在以后的计时器上启动它。如果我尝试使用timer.Stop()
停止计时器,则会显示“对象引用未设置为对象的实例。”。如果我尝试在初始化函数之外启动计时器,即使我的timer
是全局的,我也会收到相同的错误消息。
如何在Initialise
函数之外控制计时器,但调用相同的方法?
C#:
public class SmartDispatcherTimer : DispatcherTimer
{
public SmartDispatcherTimer()
{
base.Tick += SmartDispatcherTimer_Tick;
}
async void SmartDispatcherTimer_Tick(object sender, EventArgs e)
{
if (TickTask == null)
{
Console.WriteLine("No task set!");
return;
}
if (IsRunning && !IsReentrant)
{
// previous task hasn't completed
Console.WriteLine("Task already running");
return;
}
try
{
// we're running it now
IsRunning = true;
Console.WriteLine("Running Task");
await TickTask.Invoke();
Console.WriteLine("Task Completed");
}
catch (Exception ex)
{
Console.WriteLine("Task Failed");
}
finally
{
// allow it to run again
IsRunning = false;
}
}
public bool IsReentrant { get; set; }
public bool IsRunning { get; private set; }
public Func<Task> TickTask { get; set; }
}
private SmartDispatcherTimer timer;
private void Initialise()
{
try
{
timer = new SmartDispatcherTimer()
{
IsReentrant = true,
Interval = TimeSpan.FromSeconds(1),
TickTask = async () => { await GetData(); }
};
timer.Start();
}
catch (Exception ex)
{
MessageBox.Show("Task Failed");
}
}