Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated
Looks like you have a query that is taking longer than it should. From your stack trace and your code you should be able to determine exactly what query that is.
This type of timeout can have three causes;
- There's a deadlock somewhere
- The database's statistics and/or query plan cache are incorrect
- The query is too complex and needs to be tuned
A deadlock can be difficult to fix, but it's easy to determine whether that is the case. Connect to your database with Sql Server Management Studio. In the left pane right-click on the server node and select Activity Monitor. Take a look at the running processes. Normally most will be idle or running. When the problem occurs you can identify any blocked process by the process state. If you right-click on the process and select details it'll show you the last query executed by the process.
The second issue will cause the database to use a sub-optimal query plan. It can be resolved by clearing the statistics:
exec sp_updatestats
If that doesn't work you could also try
dbcc freeproccache
You should not do this when your server is under heavy load because it will temporarily incur a big performace hit as all stored procs and queries are recompiled when first executed. However, since you state the issue occurs sometimes, and the stack trace indicates your application is starting up, I think you're running a query that is only run on occasionally. You may be better off by forcing SQL Server not to reuse a previous query plan. See this answer for details on how to do that.
I've already touched on the third issue, but you can easily determine whether the query needs tuning by executing the query manually, for example using Sql Server Management Studio. If the query takes too long to complete, even after resetting the statistics you'll probably need to tune it. For help with that, you should post the exact query in a new question.
In your code where you run the stored procedure you should have something like this:
SqlCommand c = new SqlCommand(...)
//...
Add such a line of code:
c.CommandTimeout = 0;
This will wait as much time as needed for the operation to complete.
You could set the CommandTimeout
property of the SQL Command to allow for the long running SQL transaction.
You might also need to look at the SQL Query that is causing the timeout.