[英]c# Call a method every x seconds but only a certain amount of times
我希望在我的 c# 控制台應用程序中每隔 x 秒調用一次相同的方法,但我也只想調用此方法一定次數(比如 5 次)。 我需要每個方法相互運行(不能讓它們重疊)我最大的問題是控制台應用程序在完成之前關閉
我當前的代碼可以工作,但有點亂(while循環)
static void Main(string[] args)
{
for (int t = 0; t < 3; t++)
{
InitTimer(t);
}
}
public static void InitTimer(int t)
{
Console.WriteLine("Init" + t);
int x = 0;
var timer = new System.Threading.Timer(
e => x = MyMethod(x),
null,
TimeSpan.Zero,
//delay between seconds
TimeSpan.FromSeconds(5));
//number of times called
while (x < 5)
{
}
timer.Dispose();
}
public static int MyMethod(int x)
{
Console.WriteLine("Test" + x);
//call post method
x += 1;
return x;
}
}
有沒有更簡潔的方法來創建相同的功能?
你可以使用這樣的東西:
static async Task Main(string[] args)
{
var tasks = CreateTasks();
await Task.WhenAll(tasks);
}
private static IEnumerable<Task> CreateTasks()
{
var tasks = new List<Task>();
for (var t = 0; t < 3; t++)
{
var task = MyMethodAsync(t);
tasks.Add(task);
}
return tasks;
}
private static async Task MyMethodAsync(int t)
{
Console.WriteLine($"Init {t}");
var x = 0;
while (x < 5)
{
await Task.Delay(5000);
Console.WriteLine($"Test {x++}");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.