Skip to content

Instantly share code, notes, and snippets.

@JamesDunne
Created May 4, 2012 20:58
Show Gist options
  • Save JamesDunne/2597691 to your computer and use it in GitHub Desktop.
Save JamesDunne/2597691 to your computer and use it in GitHub Desktop.
SqlAsyncConnectionString wrapper class to modify a SQL connection string to add Asynchronous Processing=True if it does not exist
/// <summary>
/// Represents a connection string that is guaranteed to have been altered to enable asynchronous processing.
/// </summary>
public sealed class SqlAsyncConnectionString
{
private readonly string _connectionString;
/// <summary>
/// Creates a connection string prepared for enabling asynchronous processing with an optional connection timeout.
/// </summary>
/// <param name="connectionString">The initial connection string to modify.</param>
/// <param name="connectTimeout">Time to wait for a connection to open (in seconds). Default is 5.</param>
public SqlAsyncConnectionString(string connectionString, [Optional] int? connectTimeout)
{
// Make sure asynchronous processing is enabled for the connection string:
var csb = new SqlConnectionStringBuilder(connectionString);
csb.AsynchronousProcessing = true;
csb.ConnectTimeout = connectTimeout ?? 5;
_connectionString = csb.ConnectionString;
}
/// <summary>
/// Creates a connection string prepared for enabling asynchronous processing with a default connection timeout of 5 seconds.
/// </summary>
/// <param name="connectionString">The initial connection string to modify.</param>
public SqlAsyncConnectionString(string connectionString)
: this(connectionString, null)
{
}
public static implicit operator string(SqlAsyncConnectionString cstr)
{
return cstr._connectionString;
}
}
@JamesDunne
Copy link
Author

Still debating on whether this should be turned into a struct instead. It's just wrapping a string so there should be no need to store a separate instance on the heap and the copy-by-value should be just as cheap as copying a string reference.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment