我有一个非常简单的控制台应用程序,它将查看一个文件夹,几秒钟后它将删除所有文件。控制台应用程序需要大量的CPU资源
代码
private static void Main(string[] args)
{
ILogger logger = new LoggerWriter(ConfigurationManager.AppSettings["Log"]);
Task.Factory.StartNew(() =>
{
while (true)
{
var time = int.Parse(ConfigurationManager.AppSettings["Interval"]);
Thread.Sleep(time);
var directory = new DirectoryInfo(ConfigurationManager.AppSettings["Path"]);
foreach (var file in directory.GetFiles())
{
file.Delete();
var log = new Logger {DateTime = DateTime.Now, Action = $"File {file.FullName} will be deleted."};
logger.Write(log);
}
}
}, TaskCreationOptions.LongRunning).ContinueWith(t =>
{
if (t.Exception != null)
Console.WriteLine(t.Exception.Message);
});
Console.WriteLine("Press Ctrl+C to stop.");
while (
!(Console.KeyAvailable && (Console.ReadKey(true).Key == ConsoleKey.C) &&
(Console.ReadKey(true).Modifiers == ConsoleModifiers.Control)))
{
// do something
}
}
}
当我运行在.NET 4中的任务管理器显示在Windows Server 2008上的应用程序如下:
当我将使用FileWatcher,它是相同的情况。哪里不对?
你确定从配置中正确解析了时间吗?试着用一个常量代替它,看它变得更好。请记住它是毫秒(或使用TimeSpan) –
“时间”的值是多少? – MattC
也许日志文件被写入受监控的位置?然后它被删除,记录器再次创建,循环? – mkonvisar