Webapi2 - Return from controller action after one task completes, but continue with further Async processing

后端 未结 3 1040
南笙
南笙 2021-01-13 11:21

I have a question about Webapi2

My application is fully async/await, but I want to optimize the last part. I have a hard time finding out, so is there a

3条回答
  •  北恋
    北恋 (楼主)
    2021-01-13 11:47

    The code after the return statement will not be executed in your second example, but these tasks can be offloaded to the ThreadPool:

    public async Task Foo(Bar bar)
    {
        List tasks = new List();
        var actualresult = Barfoo(bar.Bar);
        foreach(var foobar in bar.Foo)
        {
            //some stuff which fills tasks for extra logic, not important for the client
            Task.Run(() => /* foobar task creation, queued on worker threads */);
        }
        // this will execute without waiting for the foobar logic to finish
        return Ok(actualresult.Result);
    }
    

    If you want to later check the 'extra logic' tasks for completion or errors, you may want to look into the Task Parallel Library

提交回复
热议问题