抢先看Async Stream 的最终章,在非C# 8.0 的环境下也能写出类似的效果。
如果编译器本身不支援C# 8.0 的Async Stream,还是可以做出类似的效果,这种方式称之为push model,前述三篇文章所使用的方式都是pull model。
push model 很神奇吗?在C# 中其实也不过就是Observer Pattern (观察者模式) 的应用而已, 不啰嗦,我们直接看程式码:
public class DelegateProcess
{
async static public Task ReadLineAsync(string path, Action<string> action)
{
using (StreamReader reader = File.OpenText(path))
{
while (await reader.ReadLineAsync() is string result)
{
action.Invoke(result);
await Task.Delay(100);
}
}
}
}
道理说穿了,不过就是把外部要执行的动作以Action 委派的形式当作参数传递。所以外部会这样呼叫:
await DelegateProcess.ReadLineAsync(path, (x) => Console.WriteLine(x));
解决问题的方法有很多,端看什么情境应用什么样的方式来解决而已。