当前位置: 动力学知识库 > 问答 > 编程问答 >

count down timer in C#

问题描述:

I need a count down timer in C#. Can somebody please help me to create one. The requirement is:

Set Timer = 5 minutes;

for (i=0;i<100;i++)

{

RunfunctionA();

if(TimeLeft==0)

RunfunctionB();

}

Iterations keep on running; just that when timeleft==0, RunFunctionB() should be executed.

网友答案:

That sounds as if you just need a simple StopWatch:

var sw = new StopWatch();
var maxTime = TimeSpan.FromMinutes(5);
sw.Start();
for (int i=0; i < 100; i++)
{  
    RunfunctionA();

    if(sw.Elapsed <= maxTime)
    {
        RunfunctionB();
        break;
    }
}

If you want to countdown as commented, I would just calculate the remaining time:

TimeSpan remaining = maxTime - sw.Elapsed;

Edit: according to your comments you want to stop a process that is started in RunFunctionA if the time is elapsed, you could try this approach:

private Stopwatch ProcTimer = new Stopwatch();
private TimeSpan MaxTime = TimeSpan.FromMinutes(5);

private TimeSpan Remaining { get { return MaxTime - ProcTimer.Elapsed; } }

private void RunfunctionA()
{
    using (var proc = new System.Diagnostics.Process())
    {
        // initialization
        proc.Start();
        proc.WaitForExit((int)Remaining.TotalMilliseconds);
        if (proc.HasExited)
            ;// ...
        else
            proc.Kill();
    }
}

Here is the loop:

ProcTimer.Restart();
for (int i = 0; i < 100; i++)
{
    RunfunctionA();

    if (Remaining <= TimeSpan.Zero)
    {
        RunfunctionB();
        break;
    }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: