定制等待者的任何实际用途?

nos*_*tio 3 .net c# task-parallel-library async-await

在Stephen Toub的Await Anything博客文章中有一些有趣的自定义等待者的例子.我特别喜欢await task.WithCulture()我认为在现实生活中有用的模式.但是,我想不出任何其他可能无法做到的事情TaskCompletionSource.

可能有用的一个有趣的领域是切换执行上下文,例如ControlAwaiter来自Stephen的博客或ContextSwitcher来自这个问题.然而,这不是一个好的做法,AFAIU.

看到自定义等待者的一些其他实用且有用的例子会很有趣,它们仍然不会损害代码的可读性和可维护性.

Ste*_*ary 7

自定义等待者的实际用例非常少.

但是,有一些例子,似乎适合这些类别之一:

  1. 避免Task出于性能原因.Windows应用商店平台使用自定义等待来公开其(非托管)异步操作.另一个例子是Stephen Toub 等待Socket高流量内存密集型场景中使用的专用异步API的包装器.
  2. 修改现有等待的行为.例如,ConfigureAwait(false)或者WithCurrentCulture你提到的.
  3. 启用等待的重用.此博客文章中的"event awaiter"类型满足await每个事件的提升.相反,任务只能完成一次.

Task.Yield also uses a custom awaitable, but it seems to be in a category all its own.

Personally, I avoid custom awaitables. Usually category (1) is only considered as a premature optimization. Category (2) is interesting conceptually but if you explore it out, you'll find that the behavior modifiers don't compose well. Category (3) is also interesting but more controversial IMO because the completion semantics may be surprising.