TPL Dataflow库的几个扩展函数
TPL Dataflow是微軟面向高并發(fā)應(yīng)用而推出的新程序庫。借助于異步消息傳遞與管道,它可以提供比線程池更好的控制。本身TPL庫在DataflowBlock類中提供了不少擴(kuò)展函數(shù),用起來還是非常方便的,但感覺還是不夠全(當(dāng)然,MS沒必要設(shè)計(jì)大而全的接口),前段時(shí)間寫個(gè)小程序的時(shí)候用到了它,當(dāng)時(shí)順便寫了幾個(gè)擴(kuò)展函數(shù),這里記錄一下,如果后續(xù)有擴(kuò)展再繼續(xù)補(bǔ)充。
????static class DataFlowExtension
????{
????????/// <summary>
????????///同步發(fā)送所有數(shù)據(jù)至TargetBlock
????????/// </summary>
????????public static void PostAll<T>(this ITargetBlock<T> target, IEnumerable<T> source)
????????{
????????????var isSuccess = source.All(i => target.Post(i));
????????????if (!isSuccess)
????????????{
????????????????throw new InvalidOperationException();
????????????}
????????????target.Complete();
????????}
????????/// <summary>
????????///異步發(fā)送所有數(shù)據(jù)至TargetBlock
????????/// </summary>
????????public static async Task PostAllAsync<T>(this ITargetBlock<T> target, IEnumerable<T> source)
????????{
????????????foreach (var item in source)
????????????{
????????????????await target.SendAsync(item);
????????????}
????????????target.Complete();
????????}
????????
????????/// <summary>
????????///同步從數(shù)據(jù)源中獲取所有數(shù)據(jù)
????????/// </summary>
????????public static IReadOnlyList<T> ReceiveAll<T>(this IReceivableSourceBlock<T> source)
????????{
????????????IList<T> output;
????????????if (!source.TryReceiveAll(out output))
????????????{
????????????????throw new InvalidOperationException();
????????????}
????????????return output as IReadOnlyList<T>;
????????}
????????/// <summary>
????????///異步從數(shù)據(jù)源中獲取所有數(shù)據(jù)
????????/// </summary>
????????public static async Task<IReadOnlyList<T>> ReceiveAllAsync<T>(this ISourceBlock<T> source)
????????{
????????????List<T> output = new List<T>();
????????????while (await source.OutputAvailableAsync())
????????????{
????????????????output.Add(source.Receive());
????????????}
????????????return output;
????????}
????}
這幾個(gè)擴(kuò)展函數(shù)本身是對DataflowBlock類中的函數(shù)二次封裝,沒有太多的功能,基本上每個(gè)函數(shù)都只有幾行,主要為了使用更加方便罷了,由于實(shí)現(xiàn)簡單,擴(kuò)充它也是非常方便的。
?
總結(jié)
以上是生活随笔為你收集整理的TPL Dataflow库的几个扩展函数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: WinJS实用开发技巧(2):使用art
- 下一篇: 点击费用百度竞价修改方法