我正在考虑如何在控制台应用程序上设置有限的期限。
例如,我只想给用户10秒钟的时间,让他们选择或做些什么。 如果时间超过10秒,则用户应收到警告。
这是我的代码。我试图先将其转换为字符串,然后转换为int,但是出了点问题...
using System;
using System.Threading;
namespace exercise
{
class Program
static void Main(string[] args)
{
Timer t = new Timer(TimerCallback, null, 0, 2000);
// Wait for the user to hit <Enter>
Console.ReadLine();
}
private static void TimerCallback(Object o)
{
bool loop = true; // Console.WriteLine("{0:h:mm:ss.fff}.\n", DateTime.Now); ----> Creating timer
string b = DateTime.Now.ToString();
// Display the date/time when this method got called.
Console.WriteLine("In TimerCallback: " + b);
int c = Convert.ToInt32(b);
// Force a garbage collection to occur for this demo.
if (c == 10000)
{
Console.WriteLine(" your time is runnig out , hurry up brow");
}
GC.Collect();
}
}
答案 0 :(得分:0)
您可以使用DateTime.ParseExact(“ 2009-05-08 14:40:52,531”,“ yyyy-MM-dd HH:mm:ss,fff” 将字符串传递给datetime,但是您将解析datetime,而不是传递的时间量。
您可以将呼叫次数存储在一个静态字段中,并以这种方式检查10秒钟。
class Program
{
private static int timerCounter = 1;
static void Main(string[] args)
{
Timer t = new Timer(TimerCallback, null, 0, 2000);
// Wait for the user to hit <Enter>
Console.ReadLine();
}
private static void TimerCallback(Object o)
{
bool loop = true; // Console.WriteLine("{0:h:mm:ss.fff}.\n", DateTime.Now); ----> Creating timer
string b = DateTime.Now.ToString();
// Display the date/time when this method got called.
Console.WriteLine("In TimerCallback: " + b);
// timer callback is every 2 seconds, so every 5th call is 10 sec
if (timerCounter % 5 == 0)
{
timerCounter = 1;
Console.WriteLine(" your time is runnig out , hurry up brow");
}
timerCounter++;
GC.Collect();
}
}