C# Task.WaitAll() 如何将对象状态合二为一?

How does C# Task.WaitAll() combine object states into one?

以一个简单的酒店实体为例:

class Hotel
{
    public int NumberOfRooms { get; set; }
    public int StarRating { get; set; }
}

请在 C# 5.0 中考虑以下代码:

public void Run()
{
    var hotel = new Hotel();
    var tasks = new List<Task> { SetRooms(hotel), SetStars(hotel) };
    Task.WaitAll(tasks.ToArray());
    Debug.Assert(hotel.NumberOfRooms.Equals(200));
    Debug.Assert(hotel.StarRating.Equals(5));
}

public async Task SetRooms(Hotel hotel)
{
    await Task.Delay(TimeSpan.FromSeconds(1)).ConfigureAwait(false);
    hotel.NumberOfRooms = 200;
}

public async Task SetStars(Hotel hotel)
{
    await Task.Delay(TimeSpan.FromSeconds(1)).ConfigureAwait(false);
    hotel.StarRating = 5;
}

对 Debug.Assert() 的两次调用均成功通过。我不明白在这两个任务完成后,Hotel 的实例如何包含来自 运行 并行的两种方法的分配。

我认为当 await 被调用时(在 SetRooms()SetStars() 中),酒店实例的 "snapshot" 被创建(同时具有 NumberOfRoomsStarRating 设置为 0)。所以我的期望是这两个任务之间会有竞争条件,最后一个到 运行 的任务将被复制回 hotel,在两个属性之一中产生 0。

显然我错了。你能解释一下我在哪里误解了 await 的工作原理吗?

I thought that when await is called (in both SetRooms() and SetStars()), a "snapshot" of the hotel instance is created

您的 Hotel class 是引用类型。当您使用 async-await 时,您的方法被转换为状态机,并且该状态机将 reference 提升到您的变量上。这意味着创建的两个状态机都指向 相同的 Hotel 实例 。没有 "snapshot" 或 Hotel 的深拷贝,编译器不会那样做。

如果您想查看实际发生的情况,you can have a look at what the compiler emits一旦它转换了您的异步方法:

[AsyncStateMachine(typeof(C.<SetRooms>d__1))]
public Task SetRooms(Hotel hotel)
{
    C.<SetRooms>d__1 <SetRooms>d__;
    <SetRooms>d__.hotel = hotel;
    <SetRooms>d__.<>t__builder = AsyncTaskMethodBuilder.Create();
    <SetRooms>d__.<>1__state = -1;
    AsyncTaskMethodBuilder <>t__builder = <SetRooms>d__.<>t__builder;
    <>t__builder.Start<C.<SetRooms>d__1>(ref <SetRooms>d__);
    return <SetRooms>d__.<>t__builder.Task;
}
[AsyncStateMachine(typeof(C.<SetStars>d__2))]
public Task SetStars(Hotel hotel)
{
    C.<SetStars>d__2 <SetStars>d__;
    <SetStars>d__.hotel = hotel;
    <SetStars>d__.<>t__builder = AsyncTaskMethodBuilder.Create();
    <SetStars>d__.<>1__state = -1;
    AsyncTaskMethodBuilder <>t__builder = <SetStars>d__.<>t__builder;
    <>t__builder.Start<C.<SetStars>d__2>(ref <SetStars>d__);
    return <SetStars>d__.<>t__builder.Task;
}

您可以看到这两种方法都将 hotel 变量提升到它们的状态机中。

So my expectation was that there will be a race condition between the two tasks and the last one to run will be the one copied back to hotel yielding a 0 in one of the two properties.

既然您看到了编译器实际执行的操作,您就会明白确实不存在竞争条件。这是正在修改的 Hotel 的同一个实例,每个方法设置不同的变量。


旁注

也许您编写这段代码只是为了解释您的问题,但如果您已经在创建异步方法,我建议您使用 Task.WhenAll 而不是阻塞 Task.WaitAll。这意味着将 Run 的签名更改为 async Task 而不是 void:

public async Task RunAsync()
{
    var hotel = new Hotel();
    await Task.WhenAll(SetRooms(hotel), SetStars(hotel));
    Debug.Assert(hotel.NumberOfRooms.Equals(200));
    Debug.Assert(hotel.StarRating.Equals(5));
}