【问题标题】:resetting a timer when a var is empty当 var 为空时重置计时器
【发布时间】:2013-12-18 18:42:19
【问题描述】:

我正在使用 C# 创建一个应用程序,当某些 Youtube 视频被请求并通过我创建的网站放入数据库时​​播放这些视频。然后我正在构建的程序将接受请求并在 Chrome 中打开并播放它。视频完成后,它将终止 webbrowser.exe 进程。当它终止时,该记录将从数据库中删除,因此歌曲不会再次播放。我制作的计时器将再次开始,并等待 5 分钟播放下一首歌曲。这工作正常,但问题是当数据库中没有记录时程序崩溃,我怎样才能让它再次重新启动计时器? 这是我的代码的 sn-p 问题所在;

    Execute();
    InitializeComponent();
    var aTimer = new System.Timers.Timer();
    aTimer.Elapsed += new ElapsedEventHandler((sender, e) => Execute());
    aTimer.Interval = 300000;
    aTimer.Enabled = true;
}
public void Execute()
{
    int Tijd;
    int Videolengte;
    string resultaat;
    string URL = "";

    Database db = new Database(CONNECTION_STRING);
    object[] result = db.GetFirstRecord();


        URL = (string)result[1];
        Process browser = Process.Start(@"chrome.exe",
              "http:\\www.youtube.com/watch?v=" + URL);
        Audio.SetApplicationVolume(APP, 15);

部分,我需要创建一个 if 语句来检查 var 结果是否为空,但是我可以让它再次从 aTimer 开始吗? (抱歉格式不好,我对此没有经验。

【问题讨论】:

  • 请删除所有不相关的代码,这有点乱。如果不正确,版主将为您完成格式。
  • 完成,现在看起来确实更好
  • 只需检查Execute()中的数据库是否为空,如果是则返回。计时器将在下一个间隔再次计时

标签: c# timer


【解决方案1】:

好吧,您可以检查所有数组,作为示例:

// check if there is something in the collection
if (result != null && result.Any() && result.Count >= 1)
{
    URL = result[1] as string;
    if (!string.IsNullOrEmpty(URL))
    {
       // continue safe ...
    }    
    else
    {
        // stop the timer... or something like this
        aTimer.Stop();
    }
}

为了确保aTimer.Enabled=trueaTimer.Start() 相同,例如aTimer.Enable=falseaTimer.Stop() 相同

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多