Is Task == Lazy?

前端 未结 3 1163
予麋鹿
予麋鹿 2021-01-21 05:46
public Data GetCurrent(Credentials credentials)
{ 
    var data = new Lazy(() => GetCurrentInternal(credentials));
    try
    {
        return data.Value         


        
3条回答
  •  暖寄归人
    2021-01-21 06:06

    No, Lazy is not the same as Task.


    Lazy is an implementation of the concept of lazy evaluation:

    1. It represents a T value that will be computed synchronously at first access, which may or may not occur at all.
    2. Evaluation happens at first access, and subsequent accesses use a cached value. Memoization is a closely related concept.
    3. The first access will block in order to compute the value, while subsequent accesses will yield the value immediately.

    Task is related to the concept of a future.

    1. It represents a T value that will be computed (typically asynchronously) at the creation of its promise, even if nobody ends up actually accessing it.
    2. All accesses yield a cached value that has been or will be computed by the evaluation mechanism (the promise) at a prior or future time.
    3. Any access that occurs before the computation of the value has finished will block until the calculation is complete. Any access that occurs after the computation of the value has finished will immediately yield the computed value.

    All that being said, Lazy and Task do have something in common that you may have already picked up.

    Each of these types is a unary generic type that describes a unique way to perform a particular computation that would yield a T value (and that computation can conveniently be passed as a delegate or lambda). In other words, each of these types is an example of a monad. You can find some very good and simple explanations of what a monad is here on Stack Overflow and elsewhere.

提交回复
热议问题