我的通用 Future 实现应该有一个 Completed 事件吗?
我正在编写一个通用的 Future
类,它封装了异步获取值,我注意到网络上大多数现有的实现都具有这样的合同:
public class Future<T>
{
public Future(Func<T> func); // kicks off the async operation
public T Value { get; } // gets the value and blocks if the async operation isn't done
}
这立即让我想添加一个实现的已完成事件,这样当我想要异步获取值并知道它何时完成时,我不必轮询该值。我注意到并行编程库以这种方式实现 future,但我很好奇为什么很多实现没有这个事件。我错过了什么吗?期货是否应该有已完成事件?或者这仅取决于您的背景?
I'm writing a generic Future<T>
class which encapsulates getting a value asynchronously and I've noticed most existing implementations on the web have with a contract like this:
public class Future<T>
{
public Future(Func<T> func); // kicks off the async operation
public T Value { get; } // gets the value and blocks if the async operation isn't done
}
This immediately makes me want to add a Completed event to the implementation so that I don't have to poll for the value when I want to get a value async and know when it's done. I've noticed the Parallel Programming library implements futures this way, but I was curious why a lot of implementations don't have this event. Am I missing something? Should Futures have a Completed event or not? Or does it just depend on your context?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为将类似的事情作为一个事件或 接受延续委托的方法在通用
Future
中很有用。如果您只是为了特定目的而构建它,则可能没有必要。另外,请记住,网上的示例通常只是这样,而不是生产质量的代码,它们可能会错过并非真正必要但仍然有用的功能,例如这个。
另一件需要注意的事情是,您的工作可能根本没有必要,因为此功能已经以
Task
的形式存在于框架中。I think having something like this either as an event or a method that accepts delegate to the continuation is useful in a general-purpose
Future<T>
. If you're building it just for a specific purpose, it might not be necessary.Also, keep in mind that examples on the net are often just that and not production-quality code and they might miss features that are not really necessary, but still useful, such as this one.
Another thing to note is that your work might not be necessary at all, since this functionality is already in the framework in the form of
Task<T>
.我认为这样做在某种程度上混淆了期货的概念。在我看来,future 的全部意义在于,它们允许您使用在其他顺序样式代码中异步计算的值。如果需要更明显的异步风格,那么这就是连续传递的用途。
话虽如此,这并不是我倾向于过于傲慢的抱怨。 .NET 的 Task 类结合了对两种样式的支持,到目前为止我对它非常满意。不过,我确实尝试将两种样式分开:如果我计划强制执行一项任务,那么我宁愿避免为其分配任何延续,反之亦然。
I think doing so muddies the concept of futures somewhat. In my opinion the whole point of futures is that they let you use values that are being calculated asynchronously in otherwise sequential-style code. If a more overtly asynchronous style is desired, then that's what continuation-passing is for.
That said, it's not a complaint that I'm inclined to get too uppity about. .NET's Task class combines support for both styles, and so far I've been perfectly happy with it. I do try to keep the two styles separate, though: If I plan on forcing a Task then I prefer to avoid assigning any continuations to it, and vice versa.