简体   繁体   中英

C# EF ASP.NET Web API timeout - how can I call a long running query?

I have a C# code that I want to execute.

  str = "SELECT u.LastName " +
                      ",COALESCE(COUNT(DISTINCT pc.PhraseId), 0) AS CreatedByQty " +
                      ", COALESCE(COUNT(DISTINCT pm.PhraseId), 0) AS ModifiedByQty " +
                      "FROM dbo.AspNetUsers u " +
                      "LEFT JOIN dbo.Phrase pc " +
                      "ON u.Id = pc.CreatedBy " +
                      "LEFT JOIN dbo.Phrase pm " +
                      "ON u.Id = pm.ModifiedBy " +
                      "GROUP BY u.LastName ";
                threeColQuery = db.Database.SqlQuery<threeCol>(str);
                threeColReport = await threeColQuery.ToListAsync();
                return Ok(threeColReport);

I know from running the query in SQL Server manager that it takes about 30 seconds.

When running in a Web API Call I get this:

"innerException":{"message":"An error has occurred.","exceptionMessage":"The wait operation timed 

Is there a way I can allow a WebAPI call to run a long running query?

Modifying the timeout settings on Entity Framework should do the trick.

db.Database.CommandTimeout = 60;

I would also advise against setting a global default timeout via the connection string. A minute is way too high for most queries, your 30-second query is an exception to the rule (thus you're knowingly increasing the timeout period).

By preventing all timeout exceptions across your app you lose a good indicator of another query misbehaving - leading to long term performance problems.

Increase the connection timeout with Sql.

Two approach to do that

  1. Increase the connection timeout for this query like

db.Database.CommandTimeout = 60

  1. Set the timeout property globally. For that follow this answer

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