Skip to content

Instantly share code, notes, and snippets.

@mvacha
Created August 18, 2015 19:34
Show Gist options
  • Save mvacha/0bfdd3c4b94ace75d0d9 to your computer and use it in GitHub Desktop.
Save mvacha/0bfdd3c4b94ace75d0d9 to your computer and use it in GitHub Desktop.
deadlocking
public static Task<SqlDataReader> ExecuteReaderAsync(this SqlCommand command)
{
return Task.Factory.FromAsync(command.BeginExecuteReader, command.EndExecuteReader, null);
}
public static Task<object> ExecuteScalarAsync(this SqlCommand command)
{
return command.ExecuteReaderAsync().ContinueWith((executeTask) =>
{
TaskCompletionSource<object> source = new TaskCompletionSource<object>();
if (executeTask.IsCanceled)
{
source.SetCanceled();
}
else if (executeTask.IsFaulted)
{
source.SetException(executeTask.Exception.InnerException);
}
else
{
SqlDataReader reader = executeTask.Result;
TaskEx.FromResult(reader.Read()).ContinueWith((readTask) =>
{
try
{
if (readTask.IsCanceled)
{
reader.Dispose();
source.SetCanceled();
}
else if (readTask.IsFaulted)
{
reader.Dispose();
source.SetException(readTask.Exception.InnerException);
}
else
{
Exception exception = null;
object result = null;
try
{
bool more = readTask.Result;
if (more && reader.FieldCount > 0)
{
try
{
result = reader.GetValue(0);
}
catch (Exception e)
{
exception = e;
}
}
}
finally
{
reader.Dispose();
}
if (exception != null)
{
source.SetException(exception);
}
else
{
source.SetResult(result);
}
}
}
catch (Exception e)
{
// exception thrown by Dispose...
source.SetException(e);
}
}, TaskScheduler.Default).ConfigureAwait(false);
}
return source.Task;
}, TaskScheduler.Default).Unwrap();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment