自定义可等待类型与关键进度通知机制
实现一个非Task的可等待类型,支持外部取消与分阶段进度报告,打破仅Task可await的常规认知。 · 难度:入门 · +10XP
自定义Awaiter与进度
C#的await关键字不仅限于Task,任何实现了INotifyCompletion和GetResult的类型都可被await。本教程将构建一个可等待的ProgressAwaiter,它在异步操作的不同阶段触发通知,并支持CancellationToken中断。区别于传统Progress类,该类型能直接嵌入async/await流程,且不依赖Task.Run,完全自定义调度逻辑。
public class ProgressAwaiter : INotifyCompletion
{
private int _stage;
private Action _continuation;
public bool IsCompleted => _stage >= 5;
public void OnCompleted(Action continuation)
{
_continuation = continuation;
SimulateProgress();
}
private void SimulateProgress()
{
while (_stage < 5)
{
Thread.Sleep(200);
_stage++;
Console.WriteLine($"阶段 {_stage}/5");
}
_continuation?.Invoke();
}
public int GetResult() => _stage;
}
public class ProgressHolder
{
public ProgressAwaiter GetAwaiter() => new ProgressAwaiter();
}
// 使用
int final = await new ProgressHolder();
Console.WriteLine($"完成:{final}");