Program.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 TimeOutHelper
  8. {
  9. internal class Program
  10. {
  11. static void Main(string[] args)
  12. {
  13. }
  14. public async Task RunExample()
  15. {
  16. try
  17. {
  18. // 测试一个可能超时的方法
  19. var result = await TimeHelperClass.ExecuteWithTimeout(
  20. () =>
  21. {
  22. // 模拟长时间运行的操作
  23. Thread.Sleep(5000);
  24. return "成功结果";
  25. },
  26. TimeSpan.FromSeconds(3)
  27. );
  28. Console.WriteLine($"操作完成: {result}");
  29. }
  30. catch (TimeoutException ex)
  31. {
  32. Console.WriteLine(ex.Message); // 将输出"操作在 3 秒后超时"
  33. }
  34. }
  35. public async Task RunAsyncExample()
  36. {
  37. try
  38. {
  39. var result = await TimeHelperClass.ExecuteWithTimeoutAsync(
  40. async ct =>
  41. {
  42. // 异步操作需要检查取消令牌
  43. await Task.Delay(5000, ct);
  44. return "异步成功结果";
  45. },
  46. TimeSpan.FromSeconds(3)
  47. );
  48. }
  49. catch (TimeoutException ex)
  50. {
  51. Console.WriteLine(ex.Message);
  52. }
  53. }
  54. }
  55. }