Increment variable by X every second [closed]

六眼飞鱼酱① 提交于 2019-12-13 10:02:58

问题


Am stuck at this section in code. I want a int variable to increase by X every second till (variable<=required number). Please guide me.

Edit // I am having a variable 'i'. And I want its max value to be say.. 280 I want to perform increment function on variable so that every second value of 'i' increases by 1 till (i=280)


回答1:


Do you want to make it single-threaded?

int i = 0;
while (i < max)
{
    i++;
    Thread.Sleep(x); // in milliseconds
}

or multi-threaded:

static int i = 0; // class scope

var timer = new Timer { Interval = x }; // in milliseconds
timer.Elapsed += (s,e) =>
    {
        if (++i > max)
            timer.Stop();
    };
timer.Start();



回答2:


You can create an instance of Timer class with 1 second interval (passing 1000 in the contructor) and then register the Elapsed event. Do the increment you are trying in the event handler code.




回答3:


Without any context this code should do its job:

for(int i=0; i<280; i++){
    Thread.Sleep(1000);
}

But for UI stuff you should use e.g. a Timer.



来源:https://stackoverflow.com/questions/15183244/increment-variable-by-x-every-second

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!