0Pricing
C# Academy · 课时

超时、IProgress<T> 与异步可释放对象(模拟)

使用 CancelAfter 或基于 Task.WhenAny 的超时机制,连接 IProgress 以提供适合界面的更新,并在 C# 6 中使用 try/finally 模拟异步清理。

超时、IProgress<T> 与异步可释放对象(模拟) 是 CoddyKit 上的免费 C# Academy 课时。 这是第 2 节课,共 3 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 C# Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 C# Academy 课程共包含 3 节课。

计划

目标:

  • 使用 CancelAfter 实现超时
  • 通过 Task.WhenAny 实现超时
  • 使用 IProgress<T> 报告进度
  • 在 C# 6 中使用异步清理模式(try/finally)

通过 CancelAfter 实现超时

使用 CancelAfter,并将令牌传递给异步 API;被调用方会在超时时以协作方式停止。

using System;
using System.Threading;
using System.Threading.Tasks;

public class Program
{
  static async Task<string> SlowOpAsync(CancellationToken ct)
  {
    // Simulate slow I/O that honors cancellation
    await Task.Delay(500, ct);
    return "OK";
  }

  public static void Main(string[] args)
  {
    var cts = new CancellationTokenSource();
    cts.CancelAfter(150); // timeout after 150 ms

    Task<string> t = SlowOpAsync(cts.Token);
    try
    {
      string result = t.GetAwaiter().GetResult(); // demo only
      Console.WriteLine(result);
    }
    catch (OperationCanceledException)
    {
      Console.WriteLine("Timed out");
    }
  }
}

通过 WhenAny 实现超时

Task.WhenAny 会让工作与 Task.Delay 进行竞争;如果延迟先完成,则抛出 TimeoutException。

using System;
using System.Threading.Tasks;

public class Program
{
  // Wrap any Task<T> with a timeout using WhenAny
  static async Task<T> WithTimeoutAsync<T>(Task<T> work, int milliseconds)
  {
    Task delay = Task.Delay(milliseconds);
    Task first = await Task.WhenAny(work, delay);
    if (first == work) return await work; // completed in time
    throw new TimeoutException("Operation timed out");
  }

  static async Task<int> ComputeAsync()
  {
    await Task.Delay(300); // pretend work
    return 7;
  }

  public static void Main(string[] args)
  {
    try
    {
      int v = WithTimeoutAsync(ComputeAsync(), 100).GetAwaiter().GetResult();
      Console.WriteLine("Value " + v);
    }
    catch (TimeoutException ex)
    {
      Console.WriteLine(ex.Message);
    }
  }
}

IProgress<T> 演示

IProgress<T> 将工作与 UI 解耦;生产者调用 Report,消费者安全地更新 UI 或线程。

using System;
using System.Threading.Tasks;

public class Program
{
  static async Task DownloadAsync(IProgress<int> progress)
  {
    // Report 0..100 in steps; UI would receive ProgressChanged on its context
    for (int p = 0; p <= 100; p += 25)
    {
      await Task.Delay(60);
      if (progress != null) progress.Report(p);
    }
  }

  public static void Main(string[] args)
  {
    Progress<int> prog = new Progress<int>(percent =>
    {
      Console.WriteLine("Progress: " + percent + "%");
    });

    DownloadAsync(prog).GetAwaiter().GetResult();
  }
}

异步清理模式

C# 6 不支持 IAsyncDisposable;请使用 try/finally,并在等待的工作完成后于 finally 中释放资源。

using System;
using System.IO;
using System.Threading.Tasks;

public class Program
{
  static async Task WriteThenCloseAsync(string path)
  {
    // C# 6 has no IAsyncDisposable; emulate with try/finally.
    FileStream fs = null;
    StreamWriter sw = null;
    try
    {
      fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
      sw = new StreamWriter(fs);
      await sw.WriteAsync("hello"); // do async work
      await sw.FlushAsync();        // ensure data is flushed
    }
    finally
    {
      // Dispose synchronously in finally
      if (sw != null) sw.Dispose();
      else if (fs != null) fs.Dispose();
    }
  }

  public static void Main(string[] args)
  {
    WriteThenCloseAsync("out.txt").GetAwaiter().GetResult();
    Console.WriteLine("Written");
  }
}

最佳实践

提示:

  • 对于简单的操作超时,优先使用 CancelAfter。
  • 对于自定义的超时流程,请使用 WhenAny。
  • 保持进度类型简单(例如百分比 int 或简单结构体)。
  • 释放资源前始终完成所有等待;将资源释放放在 finally 中。

超时模式

快速检查:在 C# 6 中,如何以一种不阻塞的简单方式为异步操作添加超时?

回顾

回顾:使用 CancelAfter 或 WhenAny 实现超时,通过 IProgress<T> 报告进度,并在 C# 6 中使用 try/finally 模拟异步释放。

常见问题解答

「超时、IProgress<T> 与异步可释放对象(模拟)」课时是免费的吗?

是的 — 「超时、IProgress<T> 与异步可释放对象(模拟)」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 C# Academy 课程的其余内容,请升级到 CoddyKit PRO。 C# Academy 课程共包含 3 节课。

「超时、IProgress<T> 与异步可释放对象(模拟)」这节课中我会学到什么?

使用 CancelAfter 或基于 Task.WhenAny 的超时机制,连接 IProgress 以提供适合界面的更新,并在 C# 6 中使用 try/finally 模拟异步清理。 你通过在浏览器中直接运行的动手代码来练习 C# Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 C# Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 C# Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 3 节。

「超时、IProgress<T> 与异步可释放对象(模拟)」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 C# Academy 课中编写并运行代码吗?

能。每节 C# Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. CancellationToken 模式与协作式取消
  2. 超时、IProgress 与异步可释放对象(模拟)
  3. 弹性基础:重试与退避
← 返回 C# Academy