对于必须处理如下的C#控制台批处理应用程序,这是最好的计时器方法:
连接到数据源
处理批处理,直到发生超时或处理完成。 “对数据源做一些事情”
优雅地停止控制台应用程序。
相关问题:How do you add a timer to a C# console application
最佳答案
抱歉,这是一个完整的控制台应用程序...但是这里有一个完整的控制台应用程序,可以帮助您入门。再次,我为这么多的代码表示歉意,但是其他所有人似乎都在回答:“哦,您要做的就是做到这一点” :)
using System;
using System.Collections.Generic;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static List<RunningProcess> runningProcesses = new List<RunningProcess>();
static void Main(string[] args)
{
Console.WriteLine("Starting...");
for (int i = 0; i < 100; i++)
{
DoSomethingOrTimeOut(30);
}
bool isSomethingRunning = false;
do
{
foreach (RunningProcess proc in runningProcesses)
{
// If this process is running...
if (proc.ProcessThread.ThreadState == ThreadState.Running)
{
isSomethingRunning = true;
// see if it needs to timeout...
if (DateTime.Now.Subtract(proc.StartTime).TotalSeconds > proc.TimeOutInSeconds)
{
proc.ProcessThread.Abort();
}
}
}
}
while (isSomethingRunning);
Console.WriteLine("Done!");
Console.ReadLine();
}
static void DoSomethingOrTimeOut(int timeout)
{
runningProcesses.Add(new RunningProcess
{
StartTime = DateTime.Now,
TimeOutInSeconds = timeout,
ProcessThread = new Thread(new ThreadStart(delegate
{
// do task here...
})),
});
runningProcesses[runningProcesses.Count - 1].ProcessThread.Start();
}
}
class RunningProcess
{
public int TimeOutInSeconds { get; set; }
public DateTime StartTime { get; set; }
public Thread ProcessThread { get; set; }
}
}