【问题标题】:How does C# 5.0 async work?C# 5.0 异步如何工作?
【发布时间】:2011-07-05 03:39:50
【问题描述】:

我正在尝试了解 C# 5 的新异步功能是如何工作的。假设我想开发一个原子增量函数来增加虚构的 IntStore 中的整数。仅在一个线程中对该函数进行多次调用。

async void IncrementKey(string key) {
    int i = await IntStore.Get(key);
    IntStore.Set(key, i+1);
}

在我看来,这个功能是有缺陷的。对 IncrementKey 的两次调用可以从 IntStore 返回相同的数字(例如 5),然后将其设置为 6,从而丢失其中一个增量?

如果 IntStore.Get 是异步的(返回任务)以正常工作,如何重写?

性能至关重要,是否有避免锁定的解决方案?

【问题讨论】:

    标签: asynchronous async-await c#-5.0


    【解决方案1】:

    如果你确定你只从一个线程调用你的函数,那么应该没有任何问题,因为当时只有一个对IntStore.Get 的调用可能正在等待。这是因为:

    await IncrementKey("AAA");
    await IncrementKey("BBB");
    

    在第一个 IncrementKey 完成之前,不会执行第二个 IncrementKey。代码将被转换为状态机。如果您不信任它,请将 IntStore.Get(key) 更改为:

    async Task<int> IntStore(string str) {
        Console.WriteLine("Starting IntStore");
        await TaskEx.Delay(10000);
        return 0;
    }
    

    您会看到第二个 Starting IntStore 将在第一个之后 10 秒写入。

    从这里引用http://blogs.msdn.com/b/ericlippert/archive/2010/10/29/asynchronous-programming-in-c-5-0-part-two-whence-await.aspx The “await” operator ... means “if the task we are awaiting has not yet completed then sign up the rest of this method as the continuation of that task, and then return to your caller immediately; the task will invoke the continuation when it completes.”

    【讨论】:

      猜你喜欢
      • 2011-07-05
      • 2011-05-02
      • 1970-01-01
      • 2012-12-13
      • 2013-04-15
      • 2011-05-02
      • 2013-01-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多