//-------------------------------------------------------------------------- // // Copyright (c) Microsoft Corporation. All rights reserved. // // File: TaskFactoryExtensions_FromAsync.cs // //-------------------------------------------------------------------------- namespace System.Threading.Tasks { /// Extensions for TaskFactory. public static partial class TaskFactoryExtensions { /// Creates a Task that will be completed when the specified WaitHandle is signaled. /// The target factory. /// The WaitHandle. /// The created Task. public static Task FromAsync(this TaskFactory factory, WaitHandle waitHandle) { if (factory == null) throw new ArgumentNullException("factory"); if (waitHandle == null) throw new ArgumentNullException("waitHandle"); var tcs = new TaskCompletionSource(); var rwh = ThreadPool.RegisterWaitForSingleObject(waitHandle, delegate { tcs.TrySetResult(null); }, null, -1, true); var t = tcs.Task; t.ContinueWith(_ => rwh.Unregister(null), TaskContinuationOptions.ExecuteSynchronously); return t; } } }