Statistics
| Branch: | Revision:

root / trunk / Libraries / ParallelExtensionsExtras / Extensions / TaskFactoryExtensions / TaskFactoryExtensions_FromAsync.cs @ d78cbf09

History | View | Annotate | Download (1.3 kB)

1
//--------------------------------------------------------------------------
2
// 
3
//  Copyright (c) Microsoft Corporation.  All rights reserved. 
4
// 
5
//  File: TaskFactoryExtensions_FromAsync.cs
6
//
7
//--------------------------------------------------------------------------
8

    
9
namespace System.Threading.Tasks
10
{
11
    /// <summary>Extensions for TaskFactory.</summary>
12
    public static partial class TaskFactoryExtensions
13
    {
14
        /// <summary>Creates a Task that will be completed when the specified WaitHandle is signaled.</summary>
15
        /// <param name="factory">The target factory.</param>
16
        /// <param name="waitHandle">The WaitHandle.</param>
17
        /// <returns>The created Task.</returns>
18
        public static Task FromAsync(this TaskFactory factory, WaitHandle waitHandle)
19
        {
20
            if (factory == null) throw new ArgumentNullException("factory");
21
            if (waitHandle == null) throw new ArgumentNullException("waitHandle");
22

    
23
            var tcs = new TaskCompletionSource<object>();
24
            var rwh = ThreadPool.RegisterWaitForSingleObject(waitHandle, delegate { tcs.TrySetResult(null); }, null, -1, true);
25
            var t = tcs.Task;
26
            t.ContinueWith(_ => rwh.Unregister(null), TaskContinuationOptions.ExecuteSynchronously);
27
            return t;
28
        }
29
    }
30
}