细聊.Net Core中IServiceScope的工作方式( 八 )

其实主要逻辑就是循环释放_disposables里的所有对象,也就是实现了IDisposable接口的对象 。接下来咱们再来看一下异步释放的相关逻辑 。
public ValueTask DisposeAsync(){    List<object> toDispose = BeginDispose();    if (toDispose != null)    {        try        {            for (int i = toDispose.Count - 1; i >= 0; i--)            {                object disposable = toDispose[i];                //判断是否是实现了IAsyncDisposable接口的对象                if (disposable is IAsyncDisposable asyncDisposable)                {                    //获取DisposeAsync方法返回值也就是ValueTask                    ValueTask vt = asyncDisposable.DisposeAsync();                    if (!vt.IsCompletedSuccessfully)                    {                        return Await(i, vt, toDispose);                    }                    //阻塞等待DisposeAsync执行完成                    vt.GetAwaiter().GetResult();                }                else                {                    ((IDisposable)disposable).Dispose();                }            }        }        catch (Exception ex)        {            return new ValueTask(Task.FromException(ex));        }    }    return default;    static async ValueTask Await(int i, ValueTask vt, List<object> toDispose)    {        //等待DisposeAsync方法里的逻辑执行完成        await vt.ConfigureAwait(false);        i--;        for (; i >= 0; i--)        {            object disposable = toDispose[i];            if (disposable is IAsyncDisposable asyncDisposable)            {                //等待DisposeAsync执行完成                await asyncDisposable.DisposeAsync().ConfigureAwait(false);            }            else            {                ((IDisposable)disposable).Dispose();            }        }    }}

推荐阅读