10秒后从控制台(C#)打开一个网页

时间:2015-05-27 12:43:38

标签: c#

我在C#中编写控制台应用程序。如何在10秒后打开网页?我已经找到了像

这样的东西
System.Diagnostics.Process.Start("http://www.stackoverflow.com")

但如何添加计时器?

3 个答案:

答案 0 :(得分:0)

您可以根据应用选择以下选项:

  1. System.Timers.Timer
  2. System.Windows.Forms.Timer
  3. System.Threading.Timer
  4. 例如:

    System.Threading.Thread.Sleep((int)System.TimeSpan.FromSeconds(10).TotalMilliseconds);
    

答案 1 :(得分:0)

如果您想每10秒打开一次此页

Timer timer = new Timer();
timer.Interval = 10000;
timer.Tick += timer_Tick;
timer.Start();

void timer_Tick(object sender, EventArgs e)
{
    System.Diagnostics.Process.Start("http://www.stackoverflow.com");
    timer.Stop();   //If you don't want to show page every 10 seconds stop the timer once it has shown the page.
}

如果您希望它只显示一次页面,则可以使用Stop()计时器类的方法来停止计时器。

答案 2 :(得分:0)

因为你试图在C#中打开url System.Diagnostics.Process.Start我建议您阅读this,我会复制粘贴该网页上发布的代码,以防链接在同一天被破坏:

public void OpenLink(string sUrl)
{
    try
    {
        System.Diagnostics.Process.Start(sUrl);
    }
    catch(Exception exc1)
    {
        // System.ComponentModel.Win32Exception is a known exception that occurs when Firefox is default browser.  
        // It actually opens the browser but STILL throws this exception so we can just ignore it.  If not this exception,
        // then attempt to open the URL in IE instead.
        if (exc1.GetType().ToString() != "System.ComponentModel.Win32Exception")
        {
            // sometimes throws exception so we have to just ignore
            // this is a common .NET bug that no one online really has a great reason for so now we just need to try to open
            // the URL using IE if we can.
            try
            {
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo("IExplore.exe", sUrl);
                System.Diagnostics.Process.Start(startInfo);
                startInfo = null;
            }
            catch (Exception exc2)
            {
                // still nothing we can do so just show the error to the user here.
            }
        }
    }
}

关于暂停执行,请使用Task.Delay

  var t = Task.Run(async delegate
          {
             await Task.Delay(TimeSpan.FromSeconds(10));
             return System.Diagnostics.Process.Start("http://www.stackoverflow.com");
          });

  // Here you can do whatever you want without waiting to that Task t finishes.

  t.Wait();// that's is a barrier and the code after t.Wait() will be executed only after t had returned.
  Console.WriteLine("Task returned with process {0}, t.Result); // in case System.Diagnostics.Process.Start fails t.Result should be null