TPL Dataflow库的几个扩展函数
TPL Dataflow是微軟面向高并發應用而推出的新程序庫。借助于異步消息傳遞與管道,它可以提供比線程池更好的控制。本身TPL庫在DataflowBlock類中提供了不少擴展函數,用起來還是非常方便的,但感覺還是不夠全(當然,MS沒必要設計大而全的接口),前段時間寫個小程序的時候用到了它,當時順便寫了幾個擴展函數,這里記錄一下,如果后續有擴展再繼續補充。
????static class DataFlowExtension
????{
????????/// <summary>
????????///同步發送所有數據至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>
????????///異步發送所有數據至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>
????????///同步從數據源中獲取所有數據
????????/// </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>
????????///異步從數據源中獲取所有數據
????????/// </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;
????????}
????}
這幾個擴展函數本身是對DataflowBlock類中的函數二次封裝,沒有太多的功能,基本上每個函數都只有幾行,主要為了使用更加方便罷了,由于實現簡單,擴充它也是非常方便的。
?
總結
以上是生活随笔為你收集整理的TPL Dataflow库的几个扩展函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: WinJS实用开发技巧(2):使用art
- 下一篇: 点击费用百度竞价修改方法