What's the best way to wrap a Task as a Task<TResult>

what'd
whatsapp
whatsapp app
what's
whatsapp web qr code
whatsapp desktop
whatsapp login
how to pronounce what

I am writing some async helper methods and I have APIs to support both Task and Task<T>. To re-use code, I'd like the Task-based API to wrap the given task as a Task<T> and just call through to the Task<T> API.

One way I can do this is:

private static async Task<bool> Convert(this Task @this)
{
    await @this.ConfigureAwait(false);
    return false;
}

However, I'm wondering: is there there is a better/builtin way to do this?

There is no existing Task method that does exactly this, no. Your method is fine, and is likely about as simple as you'll be able to get.

Implementing the proper error propagating/cancellation semantics using any other method is deceptively hard.

What, CAN YOU FEEL THE WEAL WITH THIS WORD OF THE DAY QUIZ? Did you collect all of last week's words, but eftsoons forget what they mean? Don't worry, we'  Quickly send and receive WhatsApp messages right from your computer.

Updated, the following propagates exceptions and cancellation:

public static class TaskExt
{
    public static Task<Empty> AsGeneric(this Task @this)
    {
        return @this.IsCompleted ?
            CompletedAsGeneric(@this) :
            @this.ContinueWith<Task<Empty>>(CompletedAsGeneric, 
                TaskContinuationOptions.ExecuteSynchronously).Unwrap();
    }

    static Task<Empty> CompletedAsGeneric(Task completedTask)
    {
        try
        {
            if (completedTask.Status != TaskStatus.RanToCompletion)
                // propagate exceptions
                completedTask.GetAwaiter().GetResult();

            // return completed task
            return Task.FromResult(Empty.Value);
        }
        catch (OperationCanceledException ex)
        {
            // propagate cancellation
            if (completedTask.IsCanceled)
                // return cancelled task
                return new Task<Empty>(() => Empty.Value, ex.CancellationToken);
            throw;
        }
    }
}

public struct Empty
{
    public static readonly Empty Value = default(Empty);
}

What are Jordan's options if Israel annexed the West Bank?, What are Jordan's options if Israel annexed the West Bank? what definition: 1. used to ask for information about people or things: 2. used in questions that show you are…. Learn more.

I've had the same requirement recently and I solved it with my own helper extension method, which allows the user to effectively wrap a Task with a Task<T>:

public static async Task<TResult> WithCompletionResult<TResult>(
    this Task sourceTask,
    TResult result
)
{
    await sourceTask;
    return result;
}

In your example call with:

Task<bool> task = myTask.WithCompletionResult<bool>(false);

If the result of Task<T> does not matter, I will use:

Task<object> task = myTask.WithCompletionResult<object>(null);

I hope this helps. If anyone knows of a pitfall with this approach let me know!

What, What definition is - —used as an interrogative expressing inquiry about the identity, nature, or value of an object or matter. How to use what in a sentence. informal a punishment or reprimand (esp in the phrase give (a person) what for) 7. what have you someone, something, or somewhere unknown or unspecified: cars, motorcycles, or what have you. 8.

Using await seems a bit overkill here. No need for the state machine here, just use a ContinueWith

private static Task<bool> Convert(this Task @this)
{
    return @this.ContinueWith(p => { p.Wait(); return false;});
}

Note: This will result in an AggregateException being wrapped unfortunately

WHAT, what definition: 1. used to ask for information about people or things: 2. used in questions that show you are…. Learn more. noun the true nature or identity of something, or the sum of its characteristics: a lecture on the whats and hows of crop rotation.

What to Cook This Week, What to Cook This Week. Momofuku's bo ssam.CreditMarcus Nilsson for The New York Times. Food stylist: Brian Preston-Campbell. WhatsApp Messenger: More than 2 billion people in over 180 countries use WhatsApp to stay in touch with friends and family, anytime and anywhere. WhatsApp is free and offers simple, secure, reliable messaging and calling, available on phones all over the world.

what, I will do what I can to help you. TranslationsEdit. show ▽what? (interrogative pronoun)  In current usage that refers to persons or things, which chiefly to things and rarely to subhuman entities, who chiefly to persons and sometimes to animals. The notion that that should not be used to refer to persons is without foundation; such use is entirely standard.

Which mask is the best? What should you avoid?, * What's going on with state border closures? Is there any point? * Can smoking help inhibit coronavirus? And Norman and Tegan discuss a few  Seen a font in use and want to know what it is? Upload an image to WhatTheFont to find the closest matches in our database.

Comments
  • whats the point of always returning false?
  • @thumbmunkeys To allow utility methods to always accept a Task<T> instead of having separate overloads to also support Task.
  • The point, I believe, is that he wants to be able to represent any Task as a Task<T>, and this is the simplest way he could think of. I would probably use Task<Unit> instead.
  • Why aren't you doing the reverse? Typically you allow a Task<T> to masquerade as a Task (since it is one).
  • @Guvante Imagine writing Task.WhenAll and only accepting Task objects. You then can't use the aggregation of the results in the continuation. But if you've written WhenAll for Task<T>, it's basically the exact same code to write the version for Task, you just ignore the return value, thus you end up writing the method twice.
  • I think we can get close to the proper error propagating/cancellation semantics (if not the same) with task.GetAwaiter().GetResult(): stackoverflow.com/a/22543052/1768303
  • @Noseratio That gives you proper error propagation, but not the proper cancellation propagation.
  • I would make that Void non-nested, so that you can actually write Task<Void> from the outside. Though something like Unit would probably be a better name, to not conflict with System.Void (which is the full name of void).
  • @svick, updated as suggested. I use Empty for this purpose in my projects.
  • @ChaseMedallion, this fiddle confirms the execution context gets flowed, as expected: dotnetfiddle.net/Gc1sus
  • He cancellation isn't propagated as cancellation; cancelled tasks are turned into faulted tasks.