Problem with C # Timer

I have a method that I want to call a method (will be referred to as myFanc) in a split stream every 3 seconds

The code below can easily do this,

 Timer myTimer = new Timer();
 myTimer.Elapsed += new ElapsedEventHandler( myFanc );
 myTimer.Interval = 3000;
 myTimer.Start();

The above code may cause a call to myFanc while another call to myFanc has not yet completed

My problem is that I also want myFanc to finish before I call it Agian, so basically I want to call the method in a separate thread every 3 seconds after myFanc is completed, how can I do this?

I don’t mind if the solution does not use the Timer class, I just want this behavior to work.

+3
source share
6 answers

AutoReset false, (.. "myFanc" ) Start .

+6

, , "myfanc",

Thread.Sleep(3000);

.

+1

myFunc

myTimer.Enabled = false;

, ,

myTimer.Enabled = true;

+1

, - Jim

using System;
using System.Timers;
using System.Threading;

class myApp
{
    public static void Main()
{
      System.Timers.Timer myTimer = new System.Timers.Timer();
      myTimer.Elapsed += new ElapsedEventHandler( myFanc );
      myTimer.Interval = 1000;
      myTimer.AutoReset = false;
      myTimer.Start();

      while ( Console.Read() != 'q' )
      {
          ;    // do nothing...
      }
    }

public static void myFanc(object source, ElapsedEventArgs e)
{
    Console.Write("\r{0}", DateTime.Now);

    Thread.Sleep(3000); //the sleep here is just to test the method, wait to be finished before another call the myFanc method is being performed
    System.Timers.Timer myTimer = new System.Timers.Timer();
    myTimer.Elapsed += new ElapsedEventHandler(myFanc);
    myTimer.Interval = 1000;
    myTimer.AutoReset = false;
    myTimer.Start();

}

}

+1

2 ,

  • myFanc. 3
  • myFanc , , .

, .. system.threading.timer - . windows.forms( - )

0

Thread.Sleep(x),

Thread thread = new Thread(new ThreadStart(myTimer));
thread.Start();


void myTimer()
{
    while (!exit)
    {
        myFunc();
        Thread.Sleep(3000);
    }
}
0

Source: https://habr.com/ru/post/1784266/


All Articles