Is Task == Lazy?

前端 未结 3 1160
予麋鹿
予麋鹿 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:10

    Task and Lazy are completely different concepts.

    You use Task to do asynchronous operations. Some boring MSDN:

    The Task class represents a single operation that does not return a value and that usually executes asynchronously. Task objects are one of the central components of the task-based asynchronous pattern first introduced in the .NET Framework 4. Because the work performed by a Task object typically executes asynchronously on a thread pool thread rather than synchronously on the main application thread, you can use the Status property, as well as the IsCanceled, IsCompleted, and IsFaulted properties, to determine the state of a task. Most commonly, a lambda expression is used to specify the work that the task is to perform.

    Lazy is used for deferred initialization of an object. It means, that your object gets initialized only when you call lazyObj.Value.

    Use lazy initialization to defer the creation of a large or resource-intensive object, or the execution of a resource-intensive task, particularly when such creation or execution might not occur during the lifetime of the program.

    To prepare for lazy initialization, you create an instance of Lazy. The type argument of the Lazy object that you create specifies the type of the object that you want to initialize lazily. The constructor that you use to create the Lazy object determines the characteristics of the initialization. Lazy initialization occurs the first time the Lazy.Value property is accessed.

提交回复
热议问题