using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace TimeOutHelper { internal class Program { static void Main(string[] args) { } public async Task RunExample() { try { // 测试一个可能超时的方法 var result = await TimeHelperClass.ExecuteWithTimeout( () => { // 模拟长时间运行的操作 Thread.Sleep(5000); return "成功结果"; }, TimeSpan.FromSeconds(3) ); Console.WriteLine($"操作完成: {result}"); } catch (TimeoutException ex) { Console.WriteLine(ex.Message); // 将输出"操作在 3 秒后超时" } } public async Task RunAsyncExample() { try { var result = await TimeHelperClass.ExecuteWithTimeoutAsync( async ct => { // 异步操作需要检查取消令牌 await Task.Delay(5000, ct); return "异步成功结果"; }, TimeSpan.FromSeconds(3) ); } catch (TimeoutException ex) { Console.WriteLine(ex.Message); } } } }