baozi
baozi

Reputation: 709

how to implicitly convert Task<A> to A using async and await?

I'm just test some async and await with simple functions. Now the output of Console.WriteLine(foo()) is System.Threading.Tasks.Task1[System.Int32]. I'd like to know how to make it return 1

static async Task<int> Delay1() { await Task.Delay(1000); return 1; }
static async Task<int> Delay2() { await Task.Delay(2000); return 2; }
static async Task<int> Delay3() { await Task.Delay(3000); return 3; }
static async Task<int> foo()
{ 
    Task<int> winningTask = await Task.WhenAny(Delay1(), Delay2(), Delay3());
    //int r = winningTask.Result;
    //return r;
    await winningTask;
    return winningTask.Result;

}

static void Main(string[] args)
{           
    Console.WriteLine("Done");
    Console.WriteLine(foo()); // 1
    Console.WriteLine(Delay1().Result);
}

Upvotes: 2

Views: 214

Answers (1)

i3arnon
i3arnon

Reputation: 116548

It seems you have some misunderstandings about the usage of async-await. await not only asynchronously waits for a task to complete, it also extracts the task's result and throws its first exception if it has one.

static async Task<int> foo()
{ 
    Task<int> winningTask = await Task.WhenAny(Delay1(), Delay2(), Delay3());
    return await winningTask;
}

As long as your method can be an async one you should use await:

static async Task Test()
{           
    Console.WriteLine("Done");
    Console.WriteLine(await foo());
    Console.WriteLine(await Delay1());
}

static void Main()
{           
    Test().Wait();
}

Upvotes: 4

Related Questions