[英]Run ASP.NET Entity Framework 6 stored procedure asynchronously
I am trying to build a page that allows the user to kick off a stored procedure and then continue to use the rest of the site without having to wait for that process to complete. 我正在尝试构建一个页面,该页面允许用户启动存储过程,然后继续使用网站的其余部分,而不必等待该过程完成。
I have tried creating a background worker thread and a secondary EDMX just for this call, but currently the site is still just unresponsive while the code runs (takes one to two minutes usually). 我曾尝试为此调用创建后台工作线程和辅助EDMX,但是当前该站点在代码运行时仍然没有响应(通常需要一到两分钟)。
protected void SaveReversal_Click(object sender, EventArgs e)
{
if (PeriodList.SelectedValue != "")
{
var bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(AsyncReverseDataload_DoWork);
bw.WorkerReportsProgress = false;
bw.WorkerSupportsCancellation = false;
bw.RunWorkerAsync(Convert.ToInt32(PeriodList.SelectedValue));
}
}
private void AsyncReverseDataload_DoWork(object sender, DoWorkEventArgs e)
{
int TrackerDetailKey = (int)e.Argument;
using (AsyncEntities ar = new AsyncEntities())
{
IObjectContextAdapter dbcontextadapter = (IObjectContextAdapter)ar;
dbcontextadapter.ObjectContext.CommandTimeout = 600;
try
{
var results = ar.ReverseDataload(TrackerDetailKey);
}
catch (Exception ex)
{
Console.Write(ex.ToString());
}
}
}
How do I get this actually running so that the site remains responsive to the user after starting the execution of the stored procedure? 我如何使它实际运行,以便站点在开始执行存储过程后仍能对用户做出响应?
since you say that it can take one or two minutes you are in a "Fire and forget" situation (at leas I think so). 因为您说可能要花费一到两分钟的时间,所以您处于“失火忘却”的境地(我认为是这样)。
Here are some options : 以下是一些选项:
-ThreadPool using Task.Run, Task.Factory.StartNew etc. However, I really think this is a bad idea! -ThreadPool使用Task.Run,Task.Factory.StartNew等。但是,我真的认为这是一个坏主意! IIS/ASP.NET has to recycle the application.
IIS / ASP.NET必须回收该应用程序。 If background thread is running when this recycling takes place,that work will be lost.
如果在进行回收时后台线程正在运行,则该工作将丢失。
-QueueBackgroundWorkItem , use this if your task goes up to 30 seconds -QueueBackgroundWorkItem,如果您的任务最多需要30秒,请使用它
-IRegisteredObject which is a background worker + a last chance -IRegisteredObject是后台工作者+最后的机会
-third party libraries "HangFire" Nito.AspNetBackgroundTasks package , check the github page how to use it. 第三方库“ HangFire” Nito.AspNetBackgroundTasks包,请检查github页面如何使用它。
-calling a method out of page scope, that is from a asmx/wcf, maybe embedded in project. -调用页面范围之外的方法,该方法来自asmx / wcf,可能嵌入在项目中。
besides all of these I would go for a Reliable Solution which is 除了所有这些,我会寻求一个可靠的解决方案
-Console app or -控制台应用程序或
-Service , on which tasks could be added from you WebApp directly in the "Tasks Queue" and then executed safely from there with logs and necessary logic. -Service,可以从WebApp直接在“任务队列”中添加任务,然后从那里安全地执行日志和必要的逻辑。
Hope this will help. 希望这会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.