All files
[pithos-ms-client] / trunk / Libraries / ParallelExtensionsExtras / Extensions / EAP / EAPCommon.cs
1 //--------------------------------------------------------------------------
2 // 
3 //  Copyright (c) Microsoft Corporation.  All rights reserved. 
4 // 
5 //  File: EAPCommon.cs
6 //
7 //--------------------------------------------------------------------------
8
9 using System.ComponentModel;
10
11 namespace System.Threading.Tasks
12 {
13     internal class EAPCommon
14     {
15         internal static void HandleCompletion<T>(
16             TaskCompletionSource<T> tcs, AsyncCompletedEventArgs e, Func<T> getResult, Action unregisterHandler)
17         {
18             // Transfers the results from the AsyncCompletedEventArgs and getResult() to the
19             // TaskCompletionSource, but only AsyncCompletedEventArg's UserState matches the TCS
20             // (this check is important if the same WebClient is used for multiple, asynchronous
21             // operations concurrently).  Also unregisters the handler to avoid a leak.
22             if (e.UserState == tcs)
23             {
24                 if (e.Cancelled) tcs.TrySetCanceled();
25                 else if (e.Error != null) tcs.TrySetException(e.Error);
26                 else tcs.TrySetResult(getResult());
27                 unregisterHandler();
28             }
29         }
30     }
31 }