Should my generic Future implementation have a Completed event?
I'm writing a generic Future&开发者_StackOverflow社区lt;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?
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>
.
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.
精彩评论