浏览代码

Add a ToAsyncEnumerable overload for tasks. I always felt it was missing as there is a ToObservable overload for tasks too.

Daniel Weber 11 年之前
父节点
当前提交
4ffc384dd1
共有 1 个文件被更改,包括 34 次插入0 次删除
  1. 34 0
      Ix.NET/Source/System.Interactive.Async/AsyncEnumerable.Conversions.cs

+ 34 - 0
Ix.NET/Source/System.Interactive.Async/AsyncEnumerable.Conversions.cs

@@ -63,6 +63,40 @@ namespace System.Linq
             }
             }
         }
         }
 
 
+        public static IAsyncEnumerable<TSource> ToAsyncEnumerable<TSource>(this Task<TSource> task)
+        {
+            if (task == null)
+                throw new ArgumentNullException("task");
+
+            return Create(() =>
+            {
+                var called = 0;
+
+                return Create(
+                    (ct, tcs) =>
+                    {
+                        if (Interlocked.CompareExchange(ref called, 1, 0) == 0)
+                        {
+                            task.ContinueWith(continuedTask =>
+                            {
+                                if (continuedTask.IsCanceled)
+                                    tcs.SetCanceled();
+                                else if (continuedTask.IsFaulted)
+                                    tcs.SetException(continuedTask.Exception.InnerException);
+                                else
+                                    tcs.SetResult(true);
+                            });
+                        }
+                        else
+                            tcs.SetResult(false);
+
+                        return tcs.Task;
+                    },
+                    () => task.Result,
+                    () => { });
+            });
+        }
+
 #if !NO_RXINTERFACES
 #if !NO_RXINTERFACES
         public static IAsyncEnumerable<TSource> ToAsyncEnumerable<TSource>(this IObservable<TSource> source)
         public static IAsyncEnumerable<TSource> ToAsyncEnumerable<TSource>(this IObservable<TSource> source)
         {
         {