Reputation: 5002
Connection time outs are specified in the connectionString in web.config file like this:
"Data Source=dbs;Initial Catalog=db;"+"Integrated Security=SSPI;Connection Timeout=30"
The time is in seconds. I want to specify a connection timeout in milliseconds, say 500ms. How can I do that?
Edit 1: I want to do this to create a ping method which just checks if the database is reachable or not.
Edit 2: I have been searching for some similar solutions and this answer mentioned specifying timeout in milliseconds. So I was intrigued and wanted to find out how it can be done.
Upvotes: 1
Views: 2519
Reputation: 306
Firstly, please make sure that you are using non-pooled connections to ensure that you are always getting a fresh connection, you can do this by adding Pooling=false
to your connection string. For both of these solutions I would also recommend adding Connection Timeout=1
just to ensure that ADO.NET does not needlessly continue to open the connection after you application has given up.
For .Net 4.5 you can use the new OpenAsync
method and a CancellationToken
to achieve a short timeout (e.g. 500ms):
using (var tokenSource = new CancellationTokenSource())
using (var connection = new SqlConnection(connectionString))
{
tokenSource.CancelAfter(500);
await connection.OpenAsync(tokenSource.Token);
}
When this times out you should see the Task
returned by OpenAsync
go to the canceled state, which will result in a TaskCanceledException
For .Net 4.0 you can wrap the connection open in a Task
and wait on that for the desired time:
var openTask = Task.Factory.StartNew(() =>
{
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
}
});
openTask.ContinueWith(task =>
{
// Need to observe any exceptions here - perhaps you might log them?
var ignored = task.Exception;
}, TaskContinuationOptions.OnlyOnFaulted);
if (!openTask.Wait(500))
{
// Didn't complete
Console.WriteLine("Fail");
}
In this example, openTask.Wait()
will return a bool
that indicates if the Task
completed or not. Please be aware that in .Net 4.0 you must observe all exceptions thrown inside tasks, otherwise they will cause your program to crash.
If you need examples for versions of .Net prior to 4.0 please let me know.
Upvotes: 4