How do I kick off an entity stored procedure in EF6 async and not wait for a return?

前端 未结 2 1358
闹比i
闹比i 2021-02-19 10:09

I\'d like to just punt a call over to the SQL Server and not wait for a return. I have an imported Entity Function from a Stored Procedure that I\'d like to call asynchronously

2条回答
  •  故里飘歌
    2021-02-19 10:21

    Ahh. I was in Entity Framework land too long. Thanks for the tips. Here's what worked for me. Do you see any problems with this?

        /// 
        /// kicks off the LONG RUNNING calculations on a budget to regenerate all pre-cooked numbers.
        /// 
        /// Budget Id
        public async System.Threading.Tasks.Task RecalculateBudgetNumbersAsync(int budgetId)
        {
            await System.Threading.Tasks.Task.Factory.StartNew(() => RecalculateBudgetNumbers(budgetId));
        }
    
        public static void RecalculateBudgetNumbers(int budgetId)
        {
            //this is static so we don't use the unit of work..
            using (BMTContext ctx = new BMTContext())
            {
                ctx.UpdateLifeOfBudgetNumbers(budgetId);                
                ctx.UpdateIntervalNumbers(budgetId);                
                ctx.UpdateIntervalActivityNumbers(budgetId);
                ctx.UpdateLifeOfBudgetActivityNumbers(budgetId);
            }
        }
    

    And my test (I'm in Visual Studio 2012 so I can do an async test).

        [TestMethod]
        public async System.Threading.Tasks.Task RecalculateBudgetNumbersAsyncTest()
        {
            System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
            timer.Start();
            await repo.RecalculateBudgetNumbersAsync(budgetId);
    
            System.Console.WriteLine("RecalculateBudgetNumbersAsyncTest milliseconds: " + timer.ElapsedMilliseconds.ToString());
        }
    

    After suggestions from Matt Smith and Usr, I changed RecalculateBudgetNumbersAsync to this. I hope this is what they meant:

        public void RecalculateBudgetNumbersAsync(int budgetId)
        {
            System.Threading.Tasks.Task.Factory.StartNew(() => RecalculateBudgetNumbers(budgetId));
        }
    

提交回复
热议问题