C# 无需等待即可开始任务
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19333648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Start a Task without waiting
提问by user2873833
I am using asp.net mvc and I want to cache some data about user from database when he reaches the home page of the site. So when user requests the Home page, I want to call an async method, which makes database calls and caches data.
我正在使用 asp.net mvc 并且我想在用户到达站点的主页时从数据库中缓存一些有关用户的数据。所以当用户请求主页时,我想调用一个异步方法,它进行数据库调用并缓存数据。
Any examples of doing this would be great.
任何这样做的例子都会很棒。
采纳答案by eFloh
ThreadPool.QueueUserWorkItem((Action<object>)state =>
{
//do your async work
}, null);
or Task.StartNew(...)
或者 Task.StartNew(...)
(sorry for the brief answer, this may take you on the right track or someone can edit this to show a full example, please?)
(抱歉我的回答很简短,这可能会让您走上正轨,或者有人可以编辑它以显示完整示例,好吗?)
回答by Oliver Weichhold
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
Task.Run(()=> DoSomeAsyncStuff());
return View();
}
private async void DoSomeAsyncStuff()
{
}
}
回答by Ε Г И ? И О
I would say you call the caching method via this:
我会说你通过这个调用缓存方法:
HostingEnvironment.QueueBackgroundWorkItem(x=> CacheData());
In that way, you don't really keep the home page request waiting so the users get to see the home page immediately, while the caching happens in the background at the server.
通过这种方式,您不会真正让主页请求等待,以便用户立即看到主页,而缓存在服务器的后台进行。
PS: But yes you run a slight risk of app domain recycling screwing up your caching thread.
PS:但是,是的,您有轻微的应用程序域回收风险,会破坏您的缓存线程。