I have a simple Console Application
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
public class Program
{
static void Main(string[] args)
{
MockAPI api = new MockAPI();
Task t = api.GetVersion();
var placeBreakPoint = "breakpoint";
}
}
public class MockAPI
{
public async Task<string> GetVersion()
{
return await APIVersion();
}
private async Task<string> APIVersion()
{
await Task.Delay(3000);
return "v1.0";
}
}
}
When I ran this the first time it executed as I expect seeing the code go all the way to
await Task.Delay(3000);
and then returning to
var placeBreakPoint = "breakpoint";
before returning to
return "v1.0";
when the delay had been completed. However running the code thereafter sees the code execute as before but never return from the Task.Delay
. I'm missing something fundamental here.
You are not waiting for your task so your application ends before the task has a chance to complete.
You need to
Wait
orawait
it (which you can't do inMain
but should do anywhere else).