【问题标题】:C# restart function if caught exception [duplicate]如果捕获异常,C# 重新启动函数 [重复]
【发布时间】:2021-09-08 03:31:15
【问题描述】:

我有一个包含在 try catch 中的函数,如果出现异常,我想重做它,但从函数开始的时间不到 1 小时。如何实现这个,我应该使用某种循环吗?

public void myFunct()
{
    // start timer
    try
    {
        // do some work
    }
    catch (Exception ex)
    {
        // if timer less than 1 hour, go to start of try
    }
}

【问题讨论】:

  • "但是从函数开始的时间不到 1 小时" - 这是什么意思?也可以考虑波莉
  • 是的,Polly 将是一个不错的选择。或者只是一个简单的循环。

标签: c# exception


【解决方案1】:
public void myFunct()
{
    bool restart;
    var startTimer = new System.Diagnostics.Stopwatch();
    do
    {
        restart = false;
        startTimer.Start();
        try
        {
            // do some work
        }
        catch (Exception ex)
        {
            startTimer.Stop();
            if (startTimer.Elapsed.Hours < 1)
            {
                restart = true;
                startTimer.Reset();
            }
        }
    } while (restart);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-28
    • 1970-01-01
    • 1970-01-01
    • 2018-10-10
    • 1970-01-01
    • 2018-11-29
    • 2012-07-13
    • 2011-12-07
    相关资源
    最近更新 更多