我想要一个运行一些处理的方法,最多持续一秒,睡5分钟,然后重复。我还希望用户能够打破睡眠并优雅地退出。我想让它在一天中运行而不会消耗太多的系统资源。什么是最好的设计模式?
这是我的第一次尝试:
这是我的代码:
var areCanContinue = new AutoResetEvent(false);
bool shouldContinue = true;
var thread = new Thread(obj =>
{
while (true)
{
areCanContinue.WaitOne(TimeSpan.FromMinutes(5));
if (shouldContinue)
{
Process();
}
else
{
break;
}
}
});
thread.Start();
string response;
do
{
Console.WriteLine("Press 'q' to quit");
response = Console.ReadLine();
} while (response != "q");
shouldContinue = false;
areCanContinue.Set();
答案 0 :(得分:4)
任务不一定是I / O绑定操作。实际上,这是Task.Delay
(内部包装计时器)的一个很好的用例:
public static async Task ProcessAsync(CancellationToken cancellationToken)
{
try
{
while (true)
{
await Task.Delay(TimeSpan.FromMinutes(5), cancellationToken).ConfigureAwait(false);
Process();
}
}
catch (TaskCanceledException)
{
// Cancellation requested, do whatever cleanup you need then exit gracefully
}
}
然后使用它:
var cancellationTokenSource = new CancellationTokenSource();
var task = ProcessAsync(cancellationTokenSource.Token);
string response;
do
{
Console.WriteLine("Press 'q' to quit");
response = Console.ReadLine();
} while (response != "q");
cancellationTokenSource.Cancel();
task.Wait(); // Wait for the task to finish
根据您的要求,您也可以直接使用计时器:
var timer = new Timer(_ => Process(), null, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5));
string response;
do
{
Console.WriteLine("Press 'q' to quit");
response = Console.ReadLine();
} while (response != "q");
timer.Dispose(); // Stop the timer
答案 1 :(得分:0)
希望这有帮助。
class Program
{
static void Main(string[] args)
{
Operation op = new Operation();
var tokenSource = new CancellationTokenSource();
Task.Factory.StartNew( async () => await op.LongRunningApplication(tokenSource.Token));
while(true)
{
Console.WriteLine("PRINT STOP for Cancellation...");
var str = Console.ReadLine();
if(string.Compare(str, "Stop", true) == 0)
{
Console.WriteLine("Cancellation Requested...");
tokenSource.Cancel();
Task.Delay(TimeSpan.FromSeconds(30)).Wait(); // Making Sure that It stops gracefully since this is console app
break;
}
}
Console.WriteLine("Completed");
}
}
public class Operation
{
public async Task LongRunningApplication(CancellationToken token)
{
Console.WriteLine("Starting long Running application....");
while (true)
{
await Task.Delay(1000); // Your Operation
Console.WriteLine("Wating...");
for (int i = 0; i < 30; i++)
{
await Task.Delay(TimeSpan.FromSeconds(10)); // Wait For 5 Mins (10 sec , 30 intervals)
if (token != null && token.IsCancellationRequested)
{
Console.WriteLine("Stopping GraceFully..");
return;
}
}
}
}
}