正規的騷操做:https://stackoverflow.com/questions/4238345/asynchronously-wait-for-taskt-to-complete-with-timeouthtml
參考資料:https://walterlv.com/post/task-wait-async-with-timeout.html#%E5%8F%82%E8%80%83%E8%B5%84%E6%96%99async
假如咱們須要這樣的遊戲規則,在規定的時間內沒有完成有關功能,就自動提示超時。post
爲了保證這個功能足夠簡單又可以說明清楚,咱們加入樸素的素數斷定spa
private static bool IsPrime(long num) { bool isPrime = false; if (num == 1) { return true; } for (var i = 2; i < num; i++) { if (num % i != 0) continue; isPrime = true; break; } return isPrime; } private static int ForPrime(int num) { int numPrime = 0; for (var i = 1; i <= num; i++) { numPrime += IsPrime(i)? 0 : 1; } return numPrime; } public static async Task<int> PrimeTask() { int val = await Task.Run(() => ForPrime(100000)); return val; }
雖然不知道處理100000個數字耗時多少,但確定1s是跑不完的,so。。。若是咱們須要在它超過1s以後提示呢,隨便提示啥都行。code
public static async Task<bool> TimeTask() { var task = PrimeTask(); int timeout = 1000; if (await Task.WhenAny(task, Task.Delay(timeout)) == task) { return true; } return false; }
代碼說明一下就是1s內處理完畢就返回true,不然就是false。htm
static void Main(string[] args) { Task<bool> t = TimeTask(); Console.WriteLine(t.Result); Console.ReadKey(); }
最後簡單的超時機制就弄好了~~blog