dev*_*eak 17 c# asp.net asp.net-mvc asp.net-ajax asp.net-mvc-2
我需要调用timer上的函数(比如onTickTack()函数)并在ASP.NET MVC项目中重新加载一些信息.我知道有几种方法可以做到这一点,但你认为哪一种最好?
注意:该函数应该只从一个地方调用,每隔X分钟调用一次,直到应用程序启动.
编辑1:重新加载一些信息 - 例如我在缓存中有一些东西,我想在计时器上更新它 - 在某个时间每天一次.
Dar*_*rov 28
这个问题的答案在很大程度上取决于你在ASP.NET MVC项目中重新加载一些信息是什么意思.这不是一个明确陈述的问题,因此,显然,它不能有明确的答案.
因此,如果我们假设您想要定期轮询一些控制器操作并更新视图上的信息,您可以使用setInterval javascript函数通过发送AJAX请求并更新UI来定期轮询服务器:
window.setInterval(function() {
// Send an AJAX request every 5s to poll for changes and update the UI
// example with jquery:
$.get('/foo', function(result) {
// TODO: use the results returned from your controller action
// to update the UI
});
}, 5000);
Run Code Online (Sandbox Code Playgroud)
另一方面,如果您定期在服务器上执行某项任务,则可以使用 RegisterWaitForSingleObject方法,如下所示:
var waitHandle = new AutoResetEvent(false);
ThreadPool.RegisterWaitForSingleObject(
waitHandle,
// Method to execute
(state, timeout) =>
{
// TODO: implement the functionality you want to be executed
// on every 5 seconds here
// Important Remark: This method runs on a worker thread drawn
// from the thread pool which is also used to service requests
// so make sure that this method returns as fast as possible or
// you will be jeopardizing worker threads which could be catastrophic
// in a web application. Make sure you don't sleep here and if you were
// to perform some I/O intensive operation make sure you use asynchronous
// API and IO completion ports for increased scalability
},
// optional state object to pass to the method
null,
// Execute the method after 5 seconds
TimeSpan.FromSeconds(5),
// Set this to false to execute it repeatedly every 5 seconds
false
);
Run Code Online (Sandbox Code Playgroud)
如果您的意思是其他内容,请不要犹豫,为您的问题提供更多详细信息.
Cha*_*ndu 12
您可以在Gllo.asax的OnApplicationStart事件中使用Timer类...
public static System.Timers.Timer timer = new System.Timers.Timer(60000); // This will raise the event every one minute.
.
.
.
timer.Enabled = true;
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
.
.
.
static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
// Do Your Stuff
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
41240 次 |
| 最近记录: |