问题描述
我需要执行一个无限的while循环,并想在global.asax
中启动执行.我的问题是我应该怎么做?我应该启动一个新线程,还是应该使用异步和任务或其他工具?在while循环中,我需要做await TaskEx.Delay(5000);
I need to execute an infinite while loop and want to initiate the execution in global.asax
.My question is how exactly should I do it? Should I start a new Thread or should I use Async and Task or anything else? Inside the while loop I need to do await TaskEx.Delay(5000);
我该怎么做,这样它才不会阻塞任何其他进程,也不会造成内存泄漏?
How do I do this so it will not block any other processes and will not create memory leaks?
我使用VS10,AsyncCTP3,MVC4
public void SignalRConnectionRecovery()
{
while (true)
{
Clients.SetConnectionTimeStamp(DateTime.UtcNow.ToString());
await TaskEx.Delay(5000);
}
}
只要应用程序可用,我要做的就是将此实例作为全局实例全局运行.
All I need to do is to run this as a singleton instance globally as long as application is available.
已解决
这是Global.asax中的最终解决方案
This is the final solution in Global.asax
protected void Application_Start()
{
Thread signalRConnectionRecovery = new Thread(SignalRConnectionRecovery);
signalRConnectionRecovery.IsBackground = true;
signalRConnectionRecovery.Start();
Application["SignalRConnectionRecovery"] = signalRConnectionRecovery;
}
protected void Application_End()
{
try
{
Thread signalRConnectionRecovery = (Thread)Application["SignalRConnectionRecovery"];
if (signalRConnectionRecovery != null && signalRConnectionRecovery.IsAlive)
{
signalRConnectionRecovery.Abort();
}
}
catch
{
///
}
}
我找到了这篇有关如何使用异步工作者的好文章: http://www.dotnetfunda.com/articles/article613-background-processes-in-asp-net-web-applications.aspx
I found this nice article about how to use async worker: http://www.dotnetfunda.com/articles/article613-background-processes-in-asp-net-web-applications.aspx
这: http://code.msdn.microsoft.com/CSASPNETBackgroundWorker-dda8d7b6
但是我认为对于我的需求,这将是完美的: http://forums.asp.net/t/1433665.aspx/1
But I think for my needs this one will be perfect:http://forums.asp.net/t/1433665.aspx/1
推荐答案
我发现了这篇有关如何使用异步工作程序的不错的文章,请尝试一下. http://www.dotnetfunda.com /articles/article613-background-processes-in-asp-net-web-applications.aspx
I found this nice article about how to use async worker, will give it a try. http://www.dotnetfunda.com/articles/article613-background-processes-in-asp-net-web-applications.aspx
这: http://code.msdn.microsoft.com/CSASPNETBackgroundWorker-dda8d7b6
但是我认为对于我的需求,这将是完美的: http://forums.asp.net/t/1433665.aspx/1
But I think for my needs this one will be perfect:http://forums.asp.net/t/1433665.aspx/1
这篇关于在ASP.NET中正确实现后台进程线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!