Home c# C # Timer and BackgroundWorker

C # Timer and BackgroundWorker

Author

Date

Category

does not work code:

protected system.timers.timer Timer;
Public Loading ()
{
  Initializecomponent ();
  backgroundworker1.runworkerasync ();
  Timer = New System.Timers.timer ();
  Timer.Autoreset = false;
  Timer.Interval = 3000;
  Timer.Enabled = True;
}
Private Void BackgroundWorker1_RunWorkerCompleted (Object Sender, System.ComponentModel.RunWorkerCompleteDeventargs E)
{
  if (! Timer.Enabled)
  {
    Main MF = new main ();
    mf.show ();
    Hide ();
  }
}

It is expected that the current window will be shown at least three seconds


Answer 1, Authority 100%

Do you just need a pause of 3 seconds? Then you absolutely do not need a Timer, nor backgroundworker.

is the easiest to do so (for WPF):

public loading ()
{
  Initializecomponent ();
  var dt = new dispatchertimer () {interval = timespan.fromseconds (3)};
  dt.tick + = (Sender, Args) = & gt; {dt.stop (); Close (); };
  dt.start ();
}

For WinForms, there is your timer: system.windows.forms.timer , which is preferable than System.timers.timer . For them, almost the same:

public loading ()
{
  Initializecomponent ();
  var t = new timer () {interval = 3000};
  t.tick + = (Sender, Args) = & gt; {t.Stop (); t.dispose (); Hide (); };
  t.start ();
}

Answer 2

You need to use the built-in event elapsed class Timer. and transfer this event to your reference to your method “backgroundworker1_runworkercompleted”

protected system.timers.timer Timer;
Public Loading ()
{
  Initializecomponent ();
  / * We connect the Elapsed event with reference to the ckgroundworker1_runworkercompleted method that is repeated every 3 seconds. * /
  Timer.elapsed + = backgroundWorker1_runworkercompleted;
  Timer = New System.Timers.timer ();
  Timer.Autoreset = True;
  Timer.Interval = 3000;
  Timer.Enabled = True;
Console.WriteLine ("Press ENTER to exit the program ...");
}
Private Void BackgroundWorker1_RunWorkerCompleted (Object Source, System.timers.elapSedeventArgs e)
{
  if (! Timer.Enabled)
  {
    Console.WriteLine ("EVERY EVENING ELAPSED TIME: {0}", E.SignalTime);
    Main MF = new main ();
    mf.show ();
    Hide ();
  }
}

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions