C# 8.0 抢先看-- Async Stream (4) push model

抢先看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));

解决问题的方法有很多,端看什么情境应用什么样的方式来解决而已。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值