我正在编写一个非常简单的c#应用程序,其中程序计数15秒,并在15秒后输出“15”。尽管该程序在前几次试验中运行良好,但它开始冻结。有谁知道为什么?我该如何改进呢?
public void timer()
{
time.Text = "restart";
int i = 0;
DateTime st1 = DateTime.Now;
String time1 = st1.Second.ToString();
int timef = Convert.ToInt32(time1);
int timef2;
while (i < 15)
{
DateTime st2 = DateTime.Now;
String time2 = st2.Second.ToString();
timef2 = Convert.ToInt32(time2);
i = timef2 - timef;
}
time.Text = i.ToString();
i = 0;
}
答案 0 :(得分:2)
如果您希望应用程序在特定数量的Timer
之后执行某些操作,则需要使用time
。
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 15 * 1000;
timer.Elapsed += timer_Elapsed;
timer.Start();
int timerCount=0;
void timer_Elapsed(object sender, EventArgs e)
{
timerCount++;
int timeElapsed = timerCount * 15;
}
答案 1 :(得分:1)
如果你知道确切的15秒就会让它变得更简单!!
Thread.Sleep(15000);
Console.WriteLine("15");
或者在计时器中使用bulit: -
static void Main(string[] args)
{
System.Timers.Timer timer = new System.Timers.Timer(15000);
timer.Elapsed += new System.Timers.ElapsedEventHandler(T_Elapsed);
timer.Start();
var i = Console.ReadLine();
}
static void T_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
Console.WriteLine("15");
var T = (Timer)sender;
T.Stop;
}
答案 2 :(得分:0)
在您的情况下,您可以使用Stopwatch - System.Diagnostics命名空间中的类:
public static void Count()
{
Stopwatch s = new Stopwatch();
int i = 0;
s.Start();
while (true)
{
if (s.ElapsedMilliseconds < i * 1000) { Thread.Sleep(10); continue; }
i += 15; Console.Write(i + " "); // or change i to 15 if you want the output to be '15' every time
}
}