Skip to content

Commit d85f836

Browse files
committed
Improved reliability of Task.GetResultOrDefault
1 parent a294b85 commit d85f836

File tree

1 file changed

+11
-19
lines changed

1 file changed

+11
-19
lines changed

Microsoft.Toolkit/Extensions/TaskExtensions.cs

Lines changed: 11 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
// The .NET Foundation licenses this file to you under the MIT license.
33
// See the LICENSE file in the project root for more information.
44

5-
using System;
65
using System.Diagnostics.CodeAnalysis;
76
using System.Diagnostics.Contracts;
87
using System.Reflection;
@@ -41,28 +40,21 @@ public static class TaskExtensions
4140
#endif
4241
)
4342
{
44-
Type taskType = task.GetType();
45-
46-
// Check if the task is actually some Task<T>
47-
if (
48-
#if NETSTANDARD1_4
49-
taskType.GetTypeInfo().IsGenericType &&
50-
#else
51-
taskType.IsGenericType &&
52-
#endif
53-
taskType.GetGenericTypeDefinition() == typeof(Task<>))
54-
{
55-
// Get the Task<T>.Result property
56-
PropertyInfo propertyInfo =
43+
// Try to get the Task<T>.Result property. This method would've
44+
// been called anyway after the type checks, but using that to
45+
// validate the input type saves some additional reflection calls.
46+
// Furthermore, doing this also makes the method flexible enough to
47+
// cases whether the input Task<T> is actually an instance of some
48+
// runtime-specific type that inherits from Task<T>.
49+
PropertyInfo? propertyInfo =
5750
#if NETSTANDARD1_4
58-
taskType.GetRuntimeProperty(nameof(Task<object>.Result));
51+
task.GetType().GetRuntimeProperty(nameof(Task<object>.Result));
5952
#else
60-
taskType.GetProperty(nameof(Task<object>.Result));
53+
task.GetType().GetProperty(nameof(Task<object>.Result));
6154
#endif
6255

63-
// Finally retrieve the result
64-
return propertyInfo!.GetValue(task);
65-
}
56+
// Return the result, if possible
57+
return propertyInfo?.GetValue(task);
6658
}
6759

6860
return null;

0 commit comments

Comments
 (0)