Waiting for async/await inside a task

前端 未结 3 750
日久生厌
日久生厌 2020-11-27 15:05

I have this construct in my main(), which creates

var tasks = new List();

var t = Task.Factory.StartNew(
    async () =>
    {
         


        
3条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 15:27

    It's discouraged to use Task.Factory.StartNew with async-await, you should be using Task.Run instead:

    var t = Task.Run(
        async () =>
        {
            Foo.Fim();
            await Foo.DoBar();
        });
    

    The Task.Factory.StartNew api was built before the Task-based Asynchronous Pattern (TAP) and async-await. It will return Task because you are starting a task with a lambda expression which happens to be async and so returns a task. Unwrap will extract the inner task, but Task.Run will implicitly do that for you.


    For a deeper comparison, there's always a relevant Stephen Toub article: Task.Run vs Task.Factory.StartNew

提交回复
热议问题