任务超时退出的方法 C#

时间:2023-03-08 22:28:38
超出时间方法退出。防止卡住。
方法:

        private static bool ImportTaskTimeout(Action method, int hours)
{
try
{
var task = Task.Run(() => method());
if (task.Wait(TimeSpan.FromHours(hours)))
return task.IsCompleted;
else
return false;
}
catch
{
return false;
}
}

或者:

 static void Main(string[] args)
{
Task t = Task.Run(() => {
Random rnd = new Random();
long sum = ;
int n = ;
for (int ctr = ; ctr <= n; ctr++)
{
int number = rnd.Next(, );
sum += number;
Console.WriteLine("ctr: {0:N0}", ctr);
}
});
TimeSpan ts = TimeSpan.FromMilliseconds();
if (!t.Wait(ts))
Console.WriteLine("The timeout interval elapsed.");
}