我正在尝试撰写政策。
我希望我的执行代码运行最长时间(在示例中为10秒)。 但我也想重试x次(样本中为3次)。并且在故障暂停之间(样本中为2秒)。
我已经操纵了我的存储过程,人为地延迟测试我的行为。
如编码(代码下方),我的数据集在30秒后填充(fyi:30秒是存储过程中的硬编码值)。所以我的执行代码不会在10秒后拯救....
理想情况下,我看到前两次尝试10秒后代码挽救,然后进行第三次尝试(因为存储过程不会人为地延迟)。显然这不是真正的代码,但奇怪的存储过程为我提供了一种测试行为的方法。
我的存储过程:
USE [Northwind]
GO
/* CREATE */ ALTER PROCEDURE [dbo].[uspWaitAndReturn]
(
@InvokeDelay bit
)
AS
SET NOCOUNT ON;
if ( @InvokeDelay > 0)
BEGIN
WAITFOR DELAY '00:00:30';
END
select top 1 * from dbo.Customers c order by newid()
GO
我的C#/ Polly /数据库代码:
public DataSet GetGenericDataSet()
{
DataSet returnDs = null;
int maxRetryAttempts = 3; /* retry attempts */
TimeSpan pauseBetweenFailuresTimeSpan = TimeSpan.FromSeconds(2); /* pause in between failures */
Policy timeoutAfter10SecondsPolicy = Policy.Timeout(TimeSpan.FromSeconds(10)); /* MAGIC SETTING here, my code inside the below .Execute block below would bail out after 10 seconds */
Policy retryThreeTimesWith2SecondsInBetweenPolicy = Policy.Handle<Exception>().WaitAndRetry(maxRetryAttempts, i => pauseBetweenFailuresTimeSpan);
Policy aggregatePolicy = timeoutAfter10SecondsPolicy.Wrap(retryThreeTimesWith2SecondsInBetweenPolicy);
int attemptCounter = 0; /* used to track the attempt and conditionally set the @InvokeDelay value for the stored procedure */
aggregatePolicy.Execute(() =>
{
try
{
attemptCounter++;
/* Microsoft.Practices.EnterpriseLibrary.Data code */
////////DatabaseProviderFactory factory = new DatabaseProviderFactory();
////////Database db = factory.CreateDefault();
////////DbCommand dbc = db.GetStoredProcCommand("dbo.uspWaitAndReturn");
////////dbc.CommandTimeout = 120;
////////db.AddInParameter(dbc, "@InvokeDelay", DbType.Boolean, attemptCounter < maxRetryAttempts ? true : false); /* if i'm not on my last attempt, then pass in true to cause the artificial delay */
////////DataSet ds;
////////ds = db.ExecuteDataSet(dbc);
////////returnDs = ds;
using (SqlConnection conn = new SqlConnection(@"MyConnectionStringValueHere"))
{
SqlCommand sqlComm = new SqlCommand("[dbo].[uspWaitAndReturn]", conn);
sqlComm.Parameters.AddWithValue("@InvokeDelay", attemptCounter < maxRetryAttempts ? true : false);
sqlComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlComm;
DataSet ds = new DataSet();
da.Fill(ds);
returnDs = ds;
}
}
catch (Exception ex)
{
string temp = ex.Message;
throw;
}
});
return returnDs;
}
使用声明:
using System;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
//// using Microsoft.Practices.EnterpriseLibrary.Data;
using Polly;
版本(packages.config)
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="CommonServiceLocator" version="1.0" targetFramework="net40" />
<package id="EnterpriseLibrary.Common" version="6.0.1304.0" targetFramework="net45" />
<package id="EnterpriseLibrary.Data" version="6.0.1304.0" targetFramework="net45" />
<package id="Polly" version="5.6.1" targetFramework="net45" />
/>
</packages>
APPEND:
在@mountain旅行者的回答很好之后,我有一个有效的例子:
重点是:
添加了TimeoutStrategy.Pessimistic
并添加了一个DbCommand.Cancel()调用(如果你不使用企业库,则为SqlCommand.Cancel())来杀死(之前的)命令,否则它们将继续运行(不好)。
我还必须“撤销”我的“政策聚合政策”。
public DataSet GetGenericDataSet()
{
DataSet returnDs = null;
DbCommand dbc = null; /* increase scope so it can be cancelled */
int maxRetryAttempts = 3; /* retry attempts */
TimeSpan pauseBetweenFailuresTimeSpan = TimeSpan.FromSeconds(2); /* pause in between failures */
Policy timeoutAfter10SecondsPolicy = Policy.Timeout(
TimeSpan.FromSeconds(10),
TimeoutStrategy.Pessimistic,
(context, timespan, task) =>
{
string x = timespan.Seconds.ToString();
if (null != dbc)
{
dbc.Cancel();
dbc = null;
}
});
Policy retryThreeTimesWith2SecondsInBetweenPolicy = Policy.Handle<Exception>().WaitAndRetry(maxRetryAttempts, i => pauseBetweenFailuresTimeSpan);
////Policy aggregatePolicy = timeoutAfter10SecondsPolicy.Wrap(retryThreeTimesWith2SecondsInBetweenPolicy);
Policy aggregatePolicy = retryThreeTimesWith2SecondsInBetweenPolicy.Wrap(timeoutAfter10SecondsPolicy);
int attemptCounter = 0; /* used to track the attempt and conditionally set the @InvokeDelay value for the stored procedure */
aggregatePolicy.Execute(() =>
{
try
{
attemptCounter++;
/* Microsoft.Practices.EnterpriseLibrary.Data code */
DatabaseProviderFactory factory = new DatabaseProviderFactory();
Database db = factory.CreateDefault();
dbc = db.GetStoredProcCommand("dbo.uspWaitAndReturn");
dbc.CommandTimeout = 120;
db.AddInParameter(dbc, "@InvokeDelay", DbType.Boolean, attemptCounter < maxRetryAttempts ? true : false); /* if i'm not on my last attempt, then pass in true to cause the artificial delay */
DataSet ds;
ds = db.ExecuteDataSet(dbc);
returnDs = ds;
////////using (SqlConnection conn = new SqlConnection(@"YOUR_VALUE_HERE"))
////////{
//////// SqlCommand sqlComm = new SqlCommand("[dbo].[uspWaitAndReturn]", conn);
//////// sqlComm.Parameters.AddWithValue("@InvokeDelay", attemptCounter < maxRetryAttempts ? true : false);
//////// sqlComm.CommandType = CommandType.StoredProcedure;
//////// SqlDataAdapter da = new SqlDataAdapter();
//////// da.SelectCommand = sqlComm;
//////// DataSet ds = new DataSet();
//////// da.Fill(ds);
//////// returnDs = ds;
////////}
}
catch (SqlException sqlex)
{
switch (sqlex.ErrorCode)
{
case -2146232060:
/* I couldn't find a more concrete way to find this specific exception, -2146232060 seems to represent alot of things */
if (!sqlex.Message.Contains("cancelled"))
{
throw;
}
break;
default:
throw;
}
}
});
return returnDs;
}
答案 0 :(得分:1)
The Polly TimeoutPolicy
comes in two modes:
Optimistic Timeout通过CancellationToken
按co-operative cancellation强制执行超时。它希望执行的代理人回复CancellationToken
。
Pessimistic Timeout对不响应CancellationToken
您正在执行的代表不尊重任何CancellationToken
。因此(对于发布的原始代码),您需要将策略配置为使用TimeoutStrategy.Pessimistic
:
Policy timeoutAfter10SecondsPolicy = Policy.Timeout(TimeSpan.FromSeconds(10), TimeoutStrategy.Pessimistic);
(在发布的原始代码中,Policy timeoutAfter10SecondsPolicy = Policy.Timeout(TimeSpan.FromSeconds(10));
采用了TimeoutStrategy.Optimistic
,因为这是默认设置。)
以上是为什么你没有看到TimeoutPolicy
在提供的代码中工作的原因。 那说:注意discussion in the Polly wiki about what pessimistic timeout means:它允许调用线程离开等待执行的委托,但不取消线程/ {{1运行该委托。因此,使用中的SQL资源不会在超时时释放。
为了确保在超时时释放SQL资源,您需要扩展代码以在超时时取消SQL操作。您可以使用SqlCommand.Cancel() method,例如this StackOverflow answer中所示。发生超时时调用的Polly Task
can be configured with an onTimeout
delegate:即配置此委托以调用相应的TimeoutPolicy
。
或者,可以将整个代码移动到异步方法,并使用类似SqlCommand.ExecuteReaderAsync(CancellationToken)的内容,以及由SqlCommand.Cancel()
驱动的Polly&#39; optimistic timeout。但这是一个更广泛的讨论。