Reputation: 3
I am trying to use a thread timer to call a method every 3 seconds over and over again. Here is the code i'm using at the moment
public void Main()
{
TextBoxMessage.Text = "Started! " + DateTime.Now.ToString();
Timer aTimer = new Timer(new TimerCallback (SendMessage), null, 3000, 3000);
}
public void SendMessage(Object sender)
{
TextBoxMessage.Text = "Timer Tick! " + DateTime.Now.ToString();
}
As of now, I get the "Started!" message but I never see the "Timer Tick!" message. This is obviously pretty basic code and I am just trying to figure out how to use this timer but have searched and searched and can't figure out what I am doing wrong.
Thanks in advance for the help!
Upvotes: 0
Views: 550
Reputation: 1
You just init the Timer object. Next step is call the method Start() to start the thread.
aTimer.Start()
Hope this help :)
Upvotes: 0
Reputation: 416179
You have a fundamental misunderstanding about how ASP.Net Webforms work.
Your web forms page is still entirely about processing HTTP requests in order to produce HTTP responses. Whenever someone views your page, an HTTP request goes to your web server. The server then creates a new instance of your Page class in order to process this request into an HTTP response. The Page class works through the ASP.Net Page Life Cycle, sends the HTTP response to the web browser, and then ASP.Net destroys the instance of your Page class to free up resources for next HTTP request. Further interactions with your Page, even postbacks to the same page by the same user, are handled by entirely new instances of the class.
Let's now apply this knowledge to your question. You want a timer running on the web server that sets a property in the Page class. It should be clear now that at the time you want the timer's elapsed code to fire, the Page object you're working with no longer exists. At best, you're causing a null reference exception on the server for trying to use an object that's not there. Or maybe the timer will prevent ASP.Net from reclaiming the old page class (eventually crashing your server when it runs out of resources). Another options is the running timer prevents the Page Life Cycle from finishing, so no response is ever sent to the user and page or browser times out. But what actually happens is that ASP.Net will destory your timer when it reclaims the page, so it won't ever even tick.
What you need to do instead is write this code in javascript to run on the client.
If you really want this to run on the server, there are options available, but they're all a LOT more complicated. One option that's relatively easy and has some traction in the ASP.Net world is SignalR.
Upvotes: 3