Reputation:
This is my first attempt of a Timer, if someone could help me out where I am going wrong it would be awesome.
I'm trying to use a while loop where if the timer hits 30 seconds try to loop it again.
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
System.Windows.Forms.Timer my_timer = new System.Windows.Forms.Timer();
my_timer = null;
//int restartticker = 30000;
while (true)
{
my_timer.Start();
if (my_timer.Equals(30000))
{
watcherprocess1();
}
my_timer = null;
}
}
Object reference not set to an instance of an object. my_timer.Start();
Upvotes: 0
Views: 2946
Reputation: 16747
This is a completely incorrect attempt to use the Timer class. my_timer.Equals(30000)
will NEVER evaluate to true, because Timer doesn't override Object.Equals()
.
If you want to do something when the timer hits 30 seconds, you have to set my_timer.Interval
to 30000 and then subscribe to the my_timer.Tick
event.
You might like to have a look at the documentation for the Timer class.
And as everyone else said, don't do my_timer = null
.
Upvotes: 1
Reputation: 273581
Your error is caused by you setting the Timer to null, to solve that just remove my_timer = null;
(2x).
But a Timer is not well suited for 'pausing' a Thread (BGW). A simple solution looks like:
while (true)
{
Thread.Sleep(30000);
watcherprocess1();
}
I spotted your previous question. The consensus (but not the accepted answer) was the advice to use a Timer instead of a Backgroundworker, not inside a Backgroundworker.
Upvotes: 4
Reputation:
Why are you creating a Timer
object, and then immediately setting it to null
?
You should subscribe to the Tick
event, and put your code in there. It should automatically loop every thirty seconds if you set its interval.
Upvotes: 1
Reputation: 245479
You initialize the timer and then set it back to null:
my_timer = null;
Which means when you call my_timer.Start()
there is no value for my_timer...hence the Exception.
Unfortunately, without some kind of better idea what you're trying to accomplish, we're not going to be able to help you with better code to get the job done.
Upvotes: 0
Reputation: 50235
It's these lines (and you should remove them):
my_timer = null;
Without code comments, I can't give you a decent alternative (i.e., I have no idea why you'd be doing that in the first place).
Upvotes: 2