正确地在ASP.NET中实现后台进程线程 [英] Correctly implement background process Thread in ASP.NET
问题描述
我需要执行一个无限while循环,并希望发起的Global.asax
执行。
我的问题是我应该究竟如何做到的呢?我应该开始一个新的线程或我应该使用异步和任务或别的什么吗?里面的while循环,我需要做等待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 == true)
{
signalRConnectionRecovery.Abort();
}
}
catch
{
///
}
}
我发现了有关如何使用异步工人这个漂亮的文章:<一href=\"http://www.dotnetfunda.com/articles/article613-background-processes-in-asp-net-web-applications.aspx\">http://www.dotnetfunda.com/articles/article613-background-processes-in-asp-net-web-applications.aspx
和这样的:
<一href=\"http://$c$c.msdn.microsoft.com/CSASPNETBackgroundWorker-dda8d7b6\">http://$c$c.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
推荐答案
我发现了有关如何使用异步工人这个漂亮的文章,会试试看。 <一href=\"http://www.dotnetfunda.com/articles/article613-background-processes-in-asp-net-web-applications.aspx\" rel=\"nofollow\">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://$c$c.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中实现后台进程线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!