如何解决连接到 Oracle DB 时异步等待 Polly 代码抛出错误 政策声明政策使用政策声明政策使用
以下是我尝试使用 Polly 保持与 Oracle 数据库的一致连接的代码。
public async Task<bool> Execute()
{
var retryTimes = 3000;
var waitBetweenExceptions = TimeSpan.FromSeconds(10);
var retryPolicy = await Policy
.Handle<OracleException>(e => e.Message.Contains("ORA-12543") || e.Message.Contains("ORA-12170"))
.WaitAndRetry(retryTimes,i => waitBetweenExceptions);
retryPolicy.Execute(() =>
{
string cs = "Data Source=SampleDB;User Id=userid;Password=password;Connection Timeout=600; Max Pool Size=150;";
using (OracleConnection connection = new OracleConnection(cs))
{
for (int i = 0; i < 1000; i++)
{
connection.open();
Console.WriteLine("Counter :" + i);
Thread.Sleep(1000);
connection.Close();
}
}
});
return true;
}
我收到的错误是 Cannot await void
编译错误。另外,我想尝试 Polly 的 WaitForever 方法。
我尝试了类似下面的问题,但对如何成功使用它几乎没有困惑。
Getting a Cannot await void,on a method that I have want to await on
编辑 修改同步方式问题
我尝试了以下代码,但仍然无法正常工作...
class Program
{
static void Main(string[] args)
{
Connect connect = new Connect();
connect.Execute();
Console.ReadKey();
}
}
public class Connect
{
public void Execute()
{
var retryTimes = 3000;
var retryableErrorCodes = new[] { "ORA-12543","ORA-12170" };
RetryPolicy retryPolicy = Policy
.Handle<OracleException>(ex => retryableErrorCodes.Any(errorCode => ex.Message.Contains(errorCode)))
.WaitAndRetry(retryTimes,_ => TimeSpan.FromSeconds(10));
retryPolicy.Execute(() =>
{
string cs = "Data Source=SampleDB;User Id=userid;Password=password;Connection Timeout=600; Max Pool Size=150;";
using (OracleConnection connection = new OracleConnection(cs))
{
for (int i = 0; i < 1000; i++)
{
connection.open();
Console.WriteLine("Counter :" + i);
Thread.Sleep(1000);
connection.Close();
}
}
});
}
}
我尝试使用同步方式。但是,断开网线后,它只是静默停止,但不会自动重新连接。
解决方法
要修饰的代码是 sync
或 async
。
同步案例
政策声明
var retryableErrorCodes = new[] { "ORA-12543","ORA-12170" };
RetryPolicy retryPolicy = Policy
.Handle<OracleException>(ex => retryableErrorCodes.Any(errorCode => ex.Message.Contains(errorCode)))
.WaitAndRetry(retryTimes,_ => TimeSpan.FromSeconds(10));
政策使用
retryPolicy.Execute(() =>
{
//...
});
异步案例
政策声明
var retryableErrorCodes = new[] { "ORA-12543","ORA-12170" };
AsyncRetryPolicy retryPolicy = Policy
.Handle<OracleException>(ex => retryableErrorCodes.Any(errorCode => ex.Message.Contains(errorCode)))
.WaitAndRetryAsync(retryTimes,_ => TimeSpan.FromSeconds(10));
政策使用
await retryPolicy.ExecuteAsync((ct) =>
{
//...
},CancellationToken.None);
WaitAndRetryForever
和 WaitAndRetryForeverAsync
相同,但您不必在那里指定最大重试次数。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。