help with c# timer
i have this timer in c#:
public class HomeController : Controller
{
public int count = 0;
public ActionResult Index()
{
Timer timer = new Timer();
timer.Interval = 1000;
timer.Elapsed += new ElapsedEventHandler(onTimer);
timer.Start();
return View();
}
public void onTimer(Object source, ElapsedEventArgs e)
{
count++;
}
[HttpPost]
public JsonResult Check开发者_JAVA技巧Status()
{
return Json(count);
}
and this is my view:
<script type="text/javascript">
$(function () {
// poll every 5 seconds
setInterval('checkStatus()', 3000);
});
function checkStatus() {
$.ajax({
url: 'Home/CheckStatus',
type: 'POST',
dataType: 'json',
success: function (xhr_data) {
document.getElementById("test").innerText = xhr_data;
}
});
}
Why does it keep show me (when running) only 0 ? why doesn't it show me: 0,1,2 etc.. ?
A new instance of the controller will be created each time you make a request. Thus your repeated AJAX calls just get 0, since that's what the count
value is initialized to.
There will likely be other controllers (with timers running) floating around until the GC runs to collect them, but they will have no effect on the new controller that is actually processing each individual request.
I don't know what problem you're trying to solve with this code, but have you investigated the setTimeout
and setInterval
javascript methods? They provide client-side timer services, and might be well-suited for your task.
If you need persistent server-side data, then there are number of options, including:
- Session state
- Application state
- ViewState
- The Cache
Which, if any, are right for you depends on the actual problem you're trying to solve.
Because your timer won't survive the page lifecycle, assuming this is ASP.NET. Every time a postback occurs, a fresh instance will be given.
I'm not sure how to get the timer to work, but to get stuff persisted across callbacks, you use something like View State, Session, or Cache.
Isn't the controller instantiated each time a request is made, so the value will be zero each time you make a request?
If you want a global counter, use Application or a static field. If you want it to count per user use session.
精彩评论