//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace System.Runtime
{
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
internal static class TaskExtensions
{
public static IAsyncResult AsAsyncResult(this Task task, AsyncCallback callback, object state)
{
if (task == null)
{
throw Fx.Exception.ArgumentNull("task");
}
if (task.Status == TaskStatus.Created)
{
throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.SFxTaskNotStarted));
}
var tcs = new TaskCompletionSource(state);
task.ContinueWith(
t =>
{
if (t.IsFaulted)
{
tcs.TrySetException(t.Exception.InnerExceptions);
}
else if (t.IsCanceled)
{
// the use of Task.ContinueWith(,TaskContinuationOptions.OnlyOnRanToCompletion)
// can give us a cancelled Task here with no t.Exception.
tcs.TrySetCanceled();
}
else
{
tcs.TrySetResult(t.Result);
}
if (callback != null)
{
callback(tcs.Task);
}
},
TaskContinuationOptions.ExecuteSynchronously);
return tcs.Task;
}
public static IAsyncResult AsAsyncResult(this Task task, AsyncCallback callback, object state)
{
if (task == null)
{
throw Fx.Exception.ArgumentNull("task");
}
if (task.Status == TaskStatus.Created)
{
throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.SFxTaskNotStarted));
}
var tcs = new TaskCompletionSource