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

3
我正在用C#编写控制台应用程序。如何在10秒后打开网页?我已经找到了类似以下代码的内容:
System.Diagnostics.Process.Start("http://www.stackoverflow.com")

但是我该如何添加一个定时器?

你需要添加计时器,它在工具箱中可用。 - Mairaj Ahmad
2
在显示的行之前放一个Thread.Sleep(10000)。或者更好地解释你真正需要的内容。 - Ralf
1
看一下 System.Threading.Timer 类。 - The Vanilla Thrilla
如果Thread.Sleep不够用,只需使用Timer或查看Task.Delay方法。 - Petr Behenský
3个回答

0

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()方法停止计时器。


我猜你在谈论Winforms计时器。但是它在控制台应用程序中根本不起作用。 - Ralf
是的,假设正在使用Windows Forms。 - Mairaj Ahmad

0

由于您正在尝试使用System.Diagnostics.Process.Start在C#中打开URL,我建议您阅读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 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接