懒人记时 代码仓库
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

64 wiersze
1.3 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace AppTime
  8. {
  9. static class Utils
  10. {
  11. public static T CheckTimeout<T>(Func<T> act, Func<Thread, T> whenTimeout, int timeoutMs, bool abortThread = true)
  12. {
  13. var isTimeout = true;
  14. Exception ex = null;
  15. var t = new Thread(() =>
  16. {
  17. try
  18. {
  19. act();
  20. isTimeout = false;
  21. }
  22. catch (Exception e)
  23. {
  24. ex = e;
  25. }
  26. });
  27. t.Start();
  28. t.Join(timeoutMs);
  29. if (isTimeout)
  30. {
  31. if (abortThread)
  32. {
  33. t.Abort();
  34. }
  35. return whenTimeout(t);
  36. }
  37. if (ex != null)
  38. {
  39. throw ex;
  40. }
  41. return default(T);
  42. }
  43. public static Exception Try(Action act)
  44. {
  45. try
  46. {
  47. act();
  48. return null;
  49. }
  50. catch (Exception ex)
  51. {
  52. return ex;
  53. }
  54. }
  55. }
  56. }