Search code examples
c#sql-serversqlcommandcommand-timeout

Is there any negative effect to setting SqlCommand's CommandTimeout to a high value?


It seems that I was running into some random issues with a Stored Procedure when it took longer than the default timeout value; I was advised of that here.

So I increased the value, and it seems to have helped.

But it makes me wonder: Why not just make it a very high number always, just in case the query or operation takes a long time? It's not as if it's going to take that long just because that is the MAX allowed, right?

And that being the case (I imagine), why would the default value be so low (30 seconds, I believe)?

UPDATE

I originally made the SqlCommand's CommandTimeout value 300 (5 minutes), but with that I got "Context Switch Deadlock occurred." So I then reduced it to 120 (2 minutes), and that seems to be more or less the "sweet spot" for me. I did get "Timeout expired" one time out of several tests, but when I retried the same exact range, it completed successfully the second time, so I guess it's just "one of those things" - 120 will sometimes not be enough of a timeout, but 300 is apparently too much. IOW, this balancing act between too little and too much doesn't appear to be "an exact science."


Solution

  • The timeout will only limit the max possible you'll wait. It won't make quick things take longer.

    Sometimes there is nothing you can do, and a feature is just ridiculous, and will take a ridiculously long time. In this case, a longer timeout is just necessary.

    However, that is hopefully not always the case, because users often don't want to wait very long. And if a user stops waiting, then you might be wasting resources creating something that won't get used. Further, you might also be making the user wait as well, should they have accidentally chosen to do more than they intended.

    My recommendation is to keep reasonable timeouts in place, and only extend them in the limited scenarios where it is necessary.

    On a completely different topic, one might be able to change the feature to make it run faster (such as filtering to work with less data, pre-aggregating intermediary totals that are faster work with, indexes, and/or query optimization.) Sometimes an index can be the difference between 2 minutes and 2 seconds.