I am trying to stop the timer when it is not in use and start it at a later timer when I need it. If I try to stop the timer using timer.Stop()
it says 'Object reference not set to an instance of an object.'. If I Try to start the timer outside the initialise function I get the same error message even though my timer
is global.
How can I control the timer outside the Initialise
function but call the same methods?
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");
}
}