Difference between Task and async Task

前端 未结 2 851
难免孤独
难免孤独 2020-12-03 10:25

C# provides two ways of creating asynchronous methods:

Task():

static Task<         


        
2条回答
  •  我在风中等你
    2020-12-03 11:12

    await is basically a shorthand for the continuation, by default using the same synchronization context for the continuation.

    For very simple examples like yours, there's not much benefit in using await - although the wrapping and unwrapping of exceptions makes for a more consistent approach.

    When you've got more complicated code, however, async makes a huge difference. Imagine you wanted:

    static async Task> MyAsync() {
        List results = new List();
        // One at a time, but each asynchronously...
        for (int i = 0; i < 10; i++) {
            // Or use LINQ, with rather a lot of care :)
            results.Add(await SomeMethodReturningString(i));
        }
        return results;
    }
    

    ... that gets much hairier with manual continuations.

    Additionally, async/await can work with types other than Task/Task so long as they implement the appropriate pattern.

    It's worth reading up more about what it's doing behind the scenes. You might want to start with MSDN.

提交回复
热议问题