forked from madelson/DistributedLock
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSqlHelpers.cs
More file actions
68 lines (62 loc) · 2.33 KB
/
Copy pathSqlHelpers.cs
File metadata and controls
68 lines (62 loc) · 2.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Medallion.Threading.Sql
{
internal static class SqlHelpers
{
public static Task<int> ExecuteNonQueryAsync(this IDbCommand command, CancellationToken cancellationToken)
{
var dbCommand = command as DbCommand;
if (dbCommand != null)
{
return cancellationToken.CanBeCanceled
? InternalExecuteNonQueryAndPropagateCancellationAsync(dbCommand, cancellationToken)
: dbCommand.ExecuteNonQueryAsync();
}
// synchronous task pattern
var taskBuilder = new TaskCompletionSource<int>();
if (cancellationToken.IsCancellationRequested)
{
taskBuilder.SetCanceled();
return taskBuilder.Task;
}
try
{
taskBuilder.SetResult(command.ExecuteNonQuery());
}
catch (Exception ex)
{
taskBuilder.SetException(ex);
}
return taskBuilder.Task;
}
private static async Task<int> InternalExecuteNonQueryAndPropagateCancellationAsync(DbCommand command, CancellationToken cancellationToken)
{
try
{
return await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
}
catch (SqlException ex)
// MA: canceled SQL operations throw SqlException when canceled instead of OCE.
// That means that downstream operations end up faulted instead of canceled. We
// wrap with OCE here to correctly propagate cancellation
when (cancellationToken.IsCancellationRequested && ex.Number == 0)
{
throw new OperationCanceledException(
"Command was canceled",
ex,
cancellationToken
);
}
}
public static bool IsClosedOrBroken(this IDbConnection connection)
=> connection.State == ConnectionState.Closed || connection.State == ConnectionState.Broken;
}
}