Run function every second Visual C#

50,459

Solution 1

SOLVED for now with

System.Threading.Thread.Sleep(700);

Solution 2

I'm not entirely clear on what you're trying to do, but, in general, you can use an object of the Timer class to specify code to be executed on a specified interval. The code would look something like this:

Timer myTimer = new Timer();
myTimer.Elapsed += new ElapsedEventHandler(DisplayTimeEvent);
myTimer.Interval = 1000; // 1000 ms is one second
myTimer.Start();

public static void DisplayTimeEvent(object source, ElapsedEventArgs e)
{
    // code here will run every second
}

Solution 3

try this

var aTimer = new System.Timers.Timer(1000);

aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

aTimer.Interval = 1000;
aTimer.Enabled = true;       

//if your code is not registers timer globally then uncomment following code

//GC.KeepAlive(aTimer);



private void OnTimedEvent(object source, ElapsedEventArgs e)
{
    draw(A, B, Pen);
}

Solution 4

You don't draw in a WinForms app, you respond to update or paint messages. Do what you want to do in the form's Paint event (or override the OnPaint method). When you want the form to be re-drawn, use Form.Invalidate. e.g. call Form.Invalidate in the timer tick...

Share:
50,459
Admin
Author by

Admin

Updated on June 19, 2020

Comments

  • Admin
    Admin almost 4 years

    I have problems with timer. I have function in function (draw in func)

    void func(){
    
     /*...do something ... */
    for(){
       for() {
      /*loop*/
    
     draw(A,B, Pen);
    
     }
    
    /*... do something ...*/
      }
    }
    

    This is draw function

       public void draw1(Point Poc, Point Kra, Pen o) {
          Graphics g = this.CreateGraphics();
          g.DrawLine(o,Poc.X+4, Poc.Y+4,Kra.X+4, Kra.Y+4);
          g.Dispose();
          }
    

    I call function 'func' on button click

    private void button4_Click(object sender, EventArgs e){
    
        func();
    
    }
    

    I want to call draw function evry second (draw the line every second). Between drawings, function needs to continue working and calculate = loop, and draw next line for some time(interval). I tried with

    timer1.Tick += new EventHandler(timer1_Tick);
    

    etc..

    private void timer1_Tick(object sender, EventArgs e)
        {
            ...
            draw(A, B, Pen)
        }
    

    etc..

    but all that stops my function, and draw one random line. I just want the time(interval) between two drawings in function 'func'. Without timer works fine, but draw all lines immediately, I need slow drawing. Cheers.