异步并等待C# - Bug?

时间:2015-02-18 07:01:03

标签: c# asynchronous async-await

这两段代码需要不同的时间才能完成,为什么?第一个需要3000毫秒,而第二个需要2000毫秒。我正在运行.Net framework 4.5和Visual Studio 2013 Ultimate。

static void Main(string[] args)
{
    var sw = new Stopwatch();
    sw.Start();            

    Task.Run(async () =>
    {
        var sw2 = new Stopwatch();
        sw2.Start();

        Task<int> t1 = GetList();
        Task<int> t2 = GetList2();

        var a = await t1;
        var b = await t2;

    }).Wait();

    sw.Stop();
    Console.WriteLine(sw.ElapsedMilliseconds + " ms");
    Console.ReadKey();
}

第二个片段:

static void Main(string[] args)
{
    var sw = new Stopwatch();
    sw.Start();            

    Task.Run(async () =>
    {
        var sw2 = new Stopwatch();
        sw2.Start();

        var a = await GetList();
        var b = await GetList2();

    }).Wait();

    sw.Stop();
    Console.WriteLine(sw.ElapsedMilliseconds + " ms");
    Console.ReadKey();
}

2 个答案:

答案 0 :(得分:3)

假设您要求执行时差。 因为这将是同步调用

var a = await GetList();
var b = await GetList2();

第一个GetList完成,然后GetList2完成,因此存在执行时间差异。

并在下面的案例中:

    Task<int> t1 = GetList();
    Task<int> t2 = GetList2();

    var a = await t1;
    var b = await t2;

GetList和GetList2将并行运行,然后你说等待第一个然后再等第二个。

答案 1 :(得分:3)

不同之处在于下面的代码启动了异步操作然后开始等待。所以它们都是并行执行然后你等待第一个,一旦完成,你就等第二个。

Task<int> t1 = GetList();
Task<int> t2 = GetList2();

var a = await t1;
var b = await t2;

第二个例子只在第一个动作完成后才开始第二个动作,因此根本没有重叠

var a = await GetList();
var b = await GetList2();