处理AsyncLazy,什么是正确的(易于使用和非泄漏)方式?

Jod*_*ell 6 c# async-await

我在他的博客中使用了Stephen Cleary的AsyncLazy实现的专业化.

/// <summary>
/// Provides support for asynchronous lazy initialization.
/// This type is fully thread-safe.
/// </summary>
/// <typeparam name="T">
/// The type of object that is being asynchronously initialized.
/// </typeparam>
public sealed class AsyncLazy<T>
{
    /// <summary>
    /// The underlying lazy task.
    /// </summary>
    private readonly Lazy<Task<T>> instance;

    /// <summary>
    /// Initializes a new instance of the 
    /// <see cref="AsyncLazy&lt;T&gt;"/> class.
    /// </summary>
    /// <param name="factory">
    /// The delegate that is invoked on a background thread to produce
    /// the value when it is needed.
    /// </param>
    /// <param name="start">
    /// If <c>true</c> commence initialization immediately.
    /// </param>
    public AsyncLazy(Func<T> factory, bool start = false)
    {
        this.instance = new Lazy<Task<T>>(() => Task.Run(factory));
        if (start)
        {
            this.Start();
        }
    }

    /// <summary>
    /// Initializes a new instance of the 
    /// <see cref="AsyncLazy&lt;T&gt;"/> class.
    /// </summary>
    /// <param name="factory">
    /// The asynchronous delegate that is invoked on a background 
    /// thread to produce the value when it is needed.
    /// </param>
    /// <param name="start">
    /// If <c>true</c> commence initialization immediately.
    /// </param>
    public AsyncLazy(Func<Task<T>> factory, bool start = false)
    {
        this.instance = new Lazy<Task<T>>(() => Task.Run(factory));
        if (start)
        {
            this.Start();
        }
    }

    /// <summary>
    /// Asynchronous infrastructure support.
    /// This method permits instances of
    /// <see cref="AsyncLazy&lt;T&gt;"/> to be await'ed.
    /// </summary>
    public TaskAwaiter<T> GetAwaiter()
    {
        return this.instance.Value.GetAwaiter();
    }

    /// <summary>
    ///     Starts the asynchronous initialization, 
    ///     if it has not already started.
    /// </summary>
    public void Start()
    {
        var unused = this.instance.Value;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是很好的代码,我真的很感激使用它是多么容易.即

class SomeClass
{
    private readonly AsyncLazy<Thing> theThing = new AsyncLazy<Thing>(
        () => new Thing());

    void SomeMethod()
    {
        var thing = await theThing;
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我的问题,

假设SomeClass继承自实现IDisposableThing实现的类IDisposable.我们有像这样的骨架实现,

class SomeClass : SomeDisposableBase
{
    private readonly AsyncLazy<Thing> theThing = new AsyncLazy<Thing>(
        () => new Thing());

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            // What do I do with theThing?
        }

        base.Dispose(disposing);
    }
}
Run Code Online (Sandbox Code Playgroud)

那么,theThingDispose覆盖中我该怎么办?我应该扩展AsyncLazy<T>到拥有新房产吗?

// ...

public bool IsStarted
{
    get
    {
        return this.instance.IsValueCreated;
    }
}

// ...
Run Code Online (Sandbox Code Playgroud)

我应该改变AsyncLazy<T>实施IDisposable吗?

我误解了,我不需要担心吗?

我应该做别的吗?

Yuv*_*kov 1

可以使用初始化bool里面的aAsyncLazy<T>来知道是否theThing已经初始化

class SomeClass : SomeDisposableBase
{
   public SomeClass()
   {
      theThing = new AsyncLazy<Thing>(() => 
      { 
         _isInitialized = true;
         return new Thing();
      } 
   }

   private bool _isInitialized;
   private readonly AsyncLazy<Thing> theThing;

protected override void Dispose(bool disposing)
{
    if (disposing && _isInitialized)
    {
        // Dispose Thing
    }

    base.Dispose(disposing);
 }
}
Run Code Online (Sandbox Code Playgroud)

虽然,如果这种模式在您的代码中多次出现,那么我肯定会扩展AsyncLazy