C# 使用Polly运行带超时的异步任务

C# 使用Polly运行带超时的异步任务,c#,async-await,polly,C#,Async Await,Polly,我有一个简单的任务,我想在后台运行。任务只需尝试移动文件即可。此任务可能会失败,因为文件正在另一个进程中使用 我想在指定的时间段内重试此操作,然后在文件仍被锁定的情况下重试timeout 我读到这本书,认为这本书非常适合我的需要 代码最终将包含在一个ASP.NET应用程序中,但我创建了一个小型控制台应用程序,试图演示我要实现的目标 这是我第一次尝试使用,因此我可能在这里完全偏离了目标,但当我在Visual Studio 2013中运行应用程序时,我收到以下错误: An unhandled exc

我有一个简单的任务,我想在后台运行。任务只需尝试移动文件即可。此任务可能会失败,因为文件正在另一个进程中使用

我想在指定的时间段内重试此操作,然后在文件仍被锁定的情况下重试
timeout

我读到这本书,认为这本书非常适合我的需要

代码最终将包含在一个
ASP.NET
应用程序中,但我创建了一个小型控制台应用程序,试图演示我要实现的目标

这是我第一次尝试使用,因此我可能在这里完全偏离了目标,但当我在
Visual Studio 2013
中运行应用程序时,我收到以下错误:

An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll

Additional information: Please use asynchronous-defined policies when calling asynchronous ExecuteAsync (and similar) methods.
代码如下:

class Program
    {
        static void Main(string[] args)
        {
            RunMyTask().GetAwaiter().GetResult();
        }

        private static async Task RunMyTask()
        {
            var timeoutPolicy = Policy.Timeout(TimeSpan.FromSeconds(20), TimeoutStrategy.Pessimistic, (context, span, arg3) => {});
            var policyResult = await timeoutPolicy.ExecuteAndCaptureAsync(async () =>
            {
                await Task.Run(() =>
                {
                    while (!MoveFiles())
                    {
                    }
                });
            });
            if (policyResult.Outcome == OutcomeType.Failure && policyResult.FinalException is TimeoutRejectedException)
            {
                Console.WriteLine("Operation Timed out");
            }
            else
            {
                Console.WriteLine("Operation succeeded!!!!!");
            }
        }

        private static bool MoveFiles()
        {
            try
            {
                var origFile = @"c:\temp\mydb.sqlite";
                var tempFile = @"c:\temp\mydb.sqlite.tmp";
                File.Move(origFile, tempFile);
                File.Move(tempFile, origFile);
                return true;
            }
            catch (Exception)
            {
                return false;
            }

        }

我做错了什么?

您需要使用
Timeout
async
变量以及
async
执行方法。Polly有每个策略的
async
变体,因此您需要一直使用
async

TimeoutPolicy timeoutPolicy = Policy
  .TimeoutAsync([int|TimeSpan|Func<TimeSpan> timeout]
                [, TimeoutStrategy.Optimistic|Pessimistic]
                [, Func<Context, TimeSpan, Task, Task> onTimeoutAsync])
TimeoutPolicy TimeoutPolicy=Policy
.TimeoutAsync([int | TimeSpan | Func timeout]
[时间超越战略乐观的|悲观的]
[,Func-onTimeoutAsync])

谢谢,我完全错过了!现在可以请客了。Polly自述文件中有关异步执行的更多详细信息: