简体   繁体   中英

await/async odd behaviour

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 or await it (which you can't do in Main but should do anywhere else).

static void Main(string[] args)
{
    MockAPI api = new MockAPI();
    Task t = api.GetVersion();
    var placeBreakPoint = "breakpoint";
    t.Wait();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM