简体   繁体   中英

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).

    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! IIS/ASP.NET has to recycle the application. 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

-IRegisteredObject which is a background worker + a last chance

-third party libraries "HangFire" Nito.AspNetBackgroundTasks package , check the github page how to use it.

-calling a method out of page scope, that is from a asmx/wcf, maybe embedded in project.

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.

Hope this will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM