当前位置: 首页>>代码示例>>C#>>正文


C# RetryPolicy.ExecuteAction方法代码示例

本文整理汇总了C#中RetryPolicy.ExecuteAction方法的典型用法代码示例。如果您正苦于以下问题:C# RetryPolicy.ExecuteAction方法的具体用法?C# RetryPolicy.ExecuteAction怎么用?C# RetryPolicy.ExecuteAction使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在RetryPolicy的用法示例。


在下文中一共展示了RetryPolicy.ExecuteAction方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: TestSqlAzureTransientErrorDetectionStrategyWithRetryableError

        [Ignore]    // REVIEW
        public void TestSqlAzureTransientErrorDetectionStrategyWithRetryableError()
        {
            int[] errors = new int[] { 40197, 40501, 40540, 10053, 10054, 10060, 40549, 40550, 40551, 40552, 40553, 40613, 40143, 233, 64 };
            Type type = typeof(SqlDatabaseTransientErrorDetectionStrategy).GetNestedType("ProcessNetLibErrorCode", BindingFlags.NonPublic);
            errors = errors.AddRange((int[])Enum.GetValues(type));

            Exception[] exceptions = FakeSqlExceptionGenerator.GenerateFakeSqlExceptions(errors);
            exceptions = exceptions.AddRange(new TimeoutException(), new EntityException("Forced Exception"));

            RetryPolicy defaultPolicy = new RetryPolicy<SqlDatabaseTransientErrorDetectionStrategy>(exceptions.Length - 1, RetryStrategy.DefaultRetryInterval);
            int execCount = 0;

            try
            {
                defaultPolicy.ExecuteAction(() =>
                {
                    Exception ex = exceptions[execCount];
                    execCount++;
                    throw ex;
                });
            }
            catch (EntityException ex)
            {
                Assert.AreEqual("Forced Exception", ex.Message);
            }

            Assert.AreEqual<int>(exceptions.Length, execCount, "The action was not executed the expected amount of times");
        }
开发者ID:HondaBey,项目名称:EnterpriseLibrary6,代码行数:29,代码来源:StrategyTests.cs

示例2: Initialize

        public void Initialize()
        {
            var retryStrategy = new Incremental(3, TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
            var retryPolicy = new RetryPolicy<ServiceBusTransientErrorDetectionStrategy>(retryStrategy);
            var tokenProvider = TokenProvider.CreateSharedSecretTokenProvider(settings.TokenIssuer, settings.TokenAccessKey);
            var serviceUri = ServiceBusEnvironment.CreateServiceUri(settings.ServiceUriScheme, settings.ServiceNamespace, settings.ServicePath);
            var namespaceManager = new NamespaceManager(serviceUri, tokenProvider);

            this.settings.Topics.AsParallel().ForAll(topic =>
            {
                retryPolicy.ExecuteAction(() => CreateTopicIfNotExists(namespaceManager, topic));
                topic.Subscriptions.AsParallel().ForAll(subscription =>
                {
                    retryPolicy.ExecuteAction(() => CreateSubscriptionIfNotExists(namespaceManager, topic, subscription));
                    retryPolicy.ExecuteAction(() => UpdateRules(namespaceManager, topic, subscription));
                });
            });

            // Execute migration support actions only after all the previous ones have been completed.
            foreach (var topic in this.settings.Topics)
            {
                foreach (var action in topic.MigrationSupport)
                {
                    retryPolicy.ExecuteAction(() => UpdateSubscriptionIfExists(namespaceManager, topic, action));
                }
            }

            this.initialized = true;
        }
开发者ID:TiagoTerra,项目名称:cqrs-journey,代码行数:29,代码来源:ServiceBusConfig.cs

示例3: Get

        // GET api/nextsession
        public Session Get()
        {
            var retryStrategy = new Incremental(5, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2));
            var retryPolicy = new RetryPolicy<SqlAzureTransientErrorDetectionStrategy>(retryStrategy);
            
            Session nextSession = new Session();
            using (VidPackEntities db = new VidPackEntities())
            {
                retryPolicy.ExecuteAction(() =>
                {
                    db.Database.Connection.Open();
                });

                ExistingSession dbSession = retryPolicy.ExecuteAction<ExistingSession>(() =>
                    db.ExistingSession.Where(item => item.IsNextSession == 1).FirstOrDefault()
                );

                if (dbSession != null)
                    nextSession = new VidPackModel.Session()
                    {
                        SessionDate = dbSession.SessionDate.ToString(),
                        SessionDescription = dbSession.SessionDescription,
                        SessionSubTitle = dbSession.SessionSubTitle,
                        SessionThumbnailUrl = String.Format("{0}{1}", ThumbnailStorageUrl, dbSession.SessionThumbnailUri),
                        SessionTitle = dbSession.SessionSubTitle,
                        SessionVideoUrl = dbSession.SessionVideoUri == null ? "" : dbSession.SessionVideoUri,
                        Speaker = dbSession.Speaker
                    };
            }
            return nextSession; 
        }
开发者ID:RobertEichenseer,项目名称:vidPACK,代码行数:32,代码来源:NextSessionController.cs

示例4: Initialize

        public void Initialize()
        {
            var retryStrategy = new Incremental(3, TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
            var retryPolicy = new RetryPolicy<ServiceBusTransientErrorDetectionStrategy>(retryStrategy);
            var tokenProvider = TokenProvider.CreateSharedSecretTokenProvider(settings.TokenIssuer, settings.TokenAccessKey);
            var serviceUri = ServiceBusEnvironment.CreateServiceUri(settings.ServiceUriScheme, settings.ServiceNamespace, settings.ServicePath);
            var namespaceManager = new NamespaceManager(serviceUri, tokenProvider);

            foreach (var topic in this.settings.Topics)
            {
                retryPolicy.ExecuteAction(() => CreateTopicIfNotExists(namespaceManager, topic));
                foreach (var subscription in topic.Subscriptions)
                {
                    retryPolicy.ExecuteAction(() => CreateSubscriptionIfNotExists(namespaceManager, topic, subscription));
                }
            }

            this.initialized = true;
        }
开发者ID:garystanford,项目名称:cqrs-journey-code,代码行数:19,代码来源:ServiceBusConfig.cs

示例5: Get

        // GET api/notification
        public IEnumerable<NotificationInfo> Get()
        {

            var retryStrategy = new Incremental(5, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2));
            var retryPolicy = new RetryPolicy<SqlAzureTransientErrorDetectionStrategy>(retryStrategy);

            List<NotificationInfo> notifications = new List<NotificationInfo>(); 
            using (VidPackEntities db = new VidPackEntities())
            {

                retryPolicy.ExecuteAction(() =>
                {
                    db.Database.Connection.Open();
                });

                notifications = retryPolicy.ExecuteAction<List<NotificationInfo>>(() =>
                        db.Notification.Select(item => new NotificationInfo() { 
                        NotificationTag = item.NotificationTag,
                    }).ToList<NotificationInfo>()
                ); 
            }
            return notifications; 
        }
开发者ID:RobertEichenseer,项目名称:vidPACK,代码行数:24,代码来源:NotificationController.cs

示例6: GetBulkRows

 public DataSet GetBulkRows()
 {
     var ds = new DataSet(TableName);
     using (var con = new SqlConnection(Connection.ConnectionString))
     {
         using (var cmd = SelectBulkRows)
         {
             var policy = new RetryPolicy<SqlTransientErrorDetectionStrategy>(2, TimeSpan.FromSeconds(5));
             cmd.Connection = con;
             con.Open();
             var adapter = new SqlDataAdapter(cmd);
             policy.ExecuteAction(() => adapter.Fill(ds, TableName));
         }
     }
     return ds;
 }
开发者ID:nhcloud,项目名称:SqlEtl,代码行数:16,代码来源:BulkInsertProvider.cs

示例7: RunDatabaseLoad

        protected override void RunDatabaseLoad(DoWorkEventArgs e)
        {
            try
            {
                // Create the Retry Policy
                var retryPolicy = new RetryPolicy<ErrorDetectionStrategy>(BackoffStrategy);

                retryPolicy.ExecuteAction(() => LoadDatabase(retryPolicy, _data));

                if (Worker.CancellationPending)
                {
                    e.Cancel = true;
                }
            }
            catch (Exception ex)
            {
                e.Result = ex.Message;
            }
        }
开发者ID:CarlRabeler,项目名称:WingTipTickets,代码行数:19,代码来源:SingleDatabaseLoader.cs

示例8: TestSqlAzureTransientErrorDetectionStrategyWithNonRetryableError

        public void TestSqlAzureTransientErrorDetectionStrategyWithNonRetryableError()
        {
            RetryPolicy defaultPolicy = new RetryPolicy<SqlAzureTransientErrorDetectionStrategy>(1, RetryStrategy.DefaultRetryInterval);
            int execCount = 0;

            try
            {
                defaultPolicy.ExecuteAction(() =>
                {
                    execCount++;
                    throw new ApplicationException("Forced Exception");
                });
            }
            catch (ApplicationException ex)
            {
                Assert.AreEqual("Forced Exception", ex.Message);
            }

            Assert.AreEqual<int>(1, execCount, "The action was not executed the expected amount of times");
        }
开发者ID:invertedtomato,项目名称:Amos2,代码行数:20,代码来源:StrategyTests.cs

示例9: TestBackoffRetryPolicyWithRetryableError

        public void TestBackoffRetryPolicyWithRetryableError()
        {
            RetryPolicy retryPolicy = new RetryPolicy<SqlAzureTransientErrorDetectionStrategy>(RetryStrategy.DefaultClientRetryCount, RetryStrategy.DefaultMinBackoff, RetryStrategy.DefaultMaxBackoff, RetryStrategy.DefaultClientBackoff);
            int execCount = 0;

            try
            {
                retryPolicy.ExecuteAction(() =>
                {
                    execCount++;

                    throw new TimeoutException("Forced Exception");
                });
            }
            catch (TimeoutException ex)
            {
                Assert.AreEqual("Forced Exception", ex.Message);
            }

            Assert.AreEqual<int>(RetryStrategy.DefaultClientRetryCount, execCount - 1, "The action was not retried using the expected amount of times");
        }
开发者ID:invertedtomato,项目名称:Amos2,代码行数:21,代码来源:SqlAzureRetryPolicyTests.cs

示例10: RetryPolityUsingCode

        private static void RetryPolityUsingCode(IUnityContainer container, IService service, OutputWriterService writer)
        {
            writer.WriteLine("Begin sample: RetryPolityUsingCode");
            // Define your retry strategy: retry 5 times, starting 1 second apart
            // and adding 2 seconds to the interval each retry.
            var retryStrategy = new Incremental(5, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2));

            // Define your retry policy using the retry strategy and the Windows Azure storage
            // transient fault detection strategy.
            var retryPolicy = new RetryPolicy<FileSystemTransientErrorDetectionStrategy>(retryStrategy);


            try
            {
                // Do some work that may result in a transient fault.
                retryPolicy.ExecuteAction(service.DoSlowAndImportantTask);
            }
            catch (Exception exception)
            {
                // All the retries failed.
                writer.WriteLine("An Exception has been thrown:\n{0}", exception);
            }
            writer.WriteLine("End sample: RetryPolityUsingCode");
        }
开发者ID:jorgeds001,项目名称:CodeSamples,代码行数:24,代码来源:Program.cs

示例11: TestThrottlingConditionSimulation

        [Ignore]    // REVIEW - Test will continue throwing the exception so the action will eventually run out of retry attempts
        public void TestThrottlingConditionSimulation()
        {
            // Instantiate a retry policy capable of detecting transient faults that are specific to SQL Database. Use the default retry count.
            RetryPolicy retryPolicy = new RetryPolicy<SqlDatabaseTransientErrorDetectionStrategy>(RetryStrategy.DefaultClientRetryCount);

            // Register a custom event handler that will be invoked by the policy whenever a retry condition is encountered.
            retryPolicy.Retrying += (sender, args) =>
            {
                // Log a warning message to indicate that a retry loop kicked in.
                Trace.TraceWarning("Retry condition encountered. Reason: {0} (retry count: {1}, retry delay: {2})", args.LastException.Message, args.CurrentRetryCount, args.Delay);

                // Make sure we are dealing with a SQL exception.
                if (args.LastException is SqlException)
                {
                    // Parse the exception to find out whether it is indicative of any throttling conditions.
                    ThrottlingCondition throttlingCondition = ThrottlingCondition.FromException(args.LastException as SqlException);

                    // Verify whether throttling condition were detected.
                    if (!throttlingCondition.IsUnknown)
                    {
                        // Log a further warning message with details on throttling conditions encountered.
                        Trace.TraceWarning("Throttling condition detected. Details: {0}", throttlingCondition);
                    }
                }
            };

            // Invoke a database operation or set of database operations against SQL Database.
            retryPolicy.ExecuteAction(() =>
            {
                // Open a connection, execute a SQL query or stored procedure, perform any kind of database operations.
                // ...

                var sqlEx = FakeSqlExceptionGenerator.GenerateFakeSqlException(ThrottlingCondition.ThrottlingErrorNumber, Resources.SampleThrottlingErrorMsg);
                throw sqlEx;
            });
        }
开发者ID:HondaBey,项目名称:EnterpriseLibrary6,代码行数:37,代码来源:ThrottlingConditionTest.cs

示例12: TestRetryPolicy

        internal static void TestRetryPolicy(RetryPolicy retryPolicy, out int retryCount, out TimeSpan totalDelay)
        {
            var callbackCount = 0;
            double totalDelayInMs = 0;

            retryPolicy.Retrying += (sender, args) =>
            {
                callbackCount++;
                totalDelayInMs += args.Delay.TotalMilliseconds;
            };

            try
            {
                retryPolicy.ExecuteAction(() => { throw new TimeoutException("Forced Exception"); });
            }
            catch (TimeoutException ex)
            {
                Assert.Equal("Forced Exception", ex.Message);
            }

            retryCount = callbackCount;
            totalDelay = TimeSpan.FromMilliseconds(totalDelayInMs);
        }
开发者ID:markcowl,项目名称:autorest,代码行数:23,代码来源:GeneralRetryPolicyTests.cs

示例13: TestBackoffRetryPolicyWithRetryableError

        public void TestBackoffRetryPolicyWithRetryableError()
        {
            const int MaxRetryCount = 4;
            RetryPolicy retryPolicy = new RetryPolicy<SqlDatabaseTransientErrorDetectionStrategy>(MaxRetryCount, TimeSpan.FromMilliseconds(500), TimeSpan.FromSeconds(1));
            int execCount = 0;

            try
            {
                retryPolicy.ExecuteAction(() =>
                {
                    execCount++;

                    throw new TimeoutException("Forced Exception");
                });
            }
            catch (TimeoutException ex)
            {
                Assert.AreEqual("Forced Exception", ex.Message);
            }

            Assert.AreEqual<int>(MaxRetryCount, execCount - 1, "The action was not retried using the expected amount of times");
        }
开发者ID:Brar,项目名称:entlib,代码行数:22,代码来源:SqlAzureRetryPolicyTests.cs

示例14: RunDatabaseLoad

        protected override void RunDatabaseLoad(DoWorkEventArgs e)
        {
            try
            {
                // Create the Retry Policy
                var retryPolicy = new RetryPolicy<ErrorDetectionStrategy>(BackoffStrategy);

                retryPolicy.ExecuteAction(() =>
                {
                    do
                    {
                        if (Worker.CancellationPending)
                        {
                            e.Cancel = true;
                            break;
                        }

                        // Load the Database & Sleep for x amount of time
                        if (CanLoadDatabase)
                        {
                            LoadDatabase(retryPolicy, _data);
                            Sleep();

                            // Switch Databases
                            IsLoadingPrimaryDatabase = !IsLoadingPrimaryDatabase;
                        }
                        else
                        {
                            Thread.Sleep(500);
                        }
                    }
                    while (TotalElapsedSeconds < ConfigHelper.Runtime);
                });
            }
            catch (Exception ex)
            {
                e.Result = ex.Message;
            }
        }
开发者ID:CarlRabeler,项目名称:WingTipTickets,代码行数:39,代码来源:DualDatabaseLoader.cs

示例15: purchaseWorker_DoWork

        void purchaseWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                object[] args = e.Argument as object[];
                if (args.Length != 8 || Convert.ToInt32(args[3]) <= 0 || Convert.ToInt32(args[4]) <= 0 || Convert.ToInt32(args[5]) <= 0 || Convert.ToInt32(args[6]) <= 0 || Convert.ToInt32(args[7]) <= 0)
                {
                    e.Result = "Please ensure you have selected a concert, ticket level, and customer, as well as supplied the ticket count and bulk purchase quantity.";
                    return;
                }
                string conn = ConstructConn(args[0].ToString(), TenantDbName, args[1].ToString(), args[2].ToString());
                string rootQuery =
                    string.Format("Insert Into Tickets (CustomerId, Name, TicketLevelId, ConcertId, PurchaseDate) Values ({0}, '', {1}, {2}, GETDATE())",
                        Convert.ToInt32(args[5]).ToString(), Convert.ToInt32(args[4]).ToString(), Convert.ToInt32(args[3]).ToString());
                string runtimeQuery = string.Empty;
                int bulkPurchase = Convert.ToInt32(args[7]);
                for (int i = 0; i < bulkPurchase; i++)
                    runtimeQuery += rootQuery + "; ";
                int ticketCount = Convert.ToInt32(args[6]);
                int purchaseCounter = 0;

                var retryPolicy = new RetryPolicy<CustomTransientErrorDetectionStrategy>(exponentialBackoffStrategy);

                retryPolicy.ExecuteAction(() =>
                {
                    using (ReliableSqlConnection reliableSqlConnection = new ReliableSqlConnection(conn, retryPolicy))
                    {
                        reliableSqlConnection.Open(retryPolicy);
                        IDbTransaction transaction = reliableSqlConnection.BeginTransaction();
                        using (var cmd = new SqlCommand(runtimeQuery, reliableSqlConnection.Current, (SqlTransaction)transaction))
                        {
                            while (purchaseCounter < ticketCount)
                            {
                                if (purchaseWorker.CancellationPending)
                                    break;
                                if (ticketCount - purchaseCounter < bulkPurchase)
                                {
                                    runtimeQuery = string.Empty;
                                    bulkPurchase = ticketCount - purchaseCounter;
                                    for (int i = 0; i < bulkPurchase; i++)
                                        runtimeQuery += rootQuery;
                                    cmd.CommandText = runtimeQuery;
                                }

                                cmd.ExecuteNonQueryWithRetry(retryPolicy);

                                purchaseWorker.ReportProgress(Convert.ToInt32(((purchaseCounter * 1.0) / ticketCount) * 100), purchaseCounter);
                                purchaseCounter = purchaseCounter + bulkPurchase;
                            }
                            transaction.Commit();
                        }
                    }
                });
                e.Result = purchaseCounter + " tickets purchased";
            }
            catch (Exception ex) { e.Result = ex.Message; }
        }
开发者ID:CarlRabeler,项目名称:WingTipTickets,代码行数:57,代码来源:MainWindow.xaml.cs


注:本文中的RetryPolicy.ExecuteAction方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。