Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

外部 dll 中含有嵌套的 using 语句时无法正确调用 Dispose() #692

Closed
Asura336 opened this issue Apr 25, 2022 · 2 comments
Closed

Comments

@Asura336
Copy link

在主工程或者主工程的依赖项定义 IDisposable 子类,外部 dll 工程从 using 语句构造它,如果使用了嵌套的 using 语句,将导致泄露。

在主工程或者主工程的依赖项中定义如下类:

using System;
using UnityEngine;

namespace Com.Test
{
    public class SampleDisposableClass<T> : IDisposable
    {
        readonly T[] arr;

        public SampleDisposableClass(int length = 8)
        {
            arr = new T[length];
        }

        public T this[int index]
        {
            get => arr[index];
            set => arr[index] = value;
        }

        private bool disposedValue;

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                Debug.Log($"Dispose({disposing}) -> {typeof(T)}");
                if (disposing)
                {
                    // pass
                }
                disposedValue = true;
            }
        }

        ~SampleDisposableClass()
        {
            Dispose(disposing: false);
#if UNITY_EDITOR || DEVELOPMENT_BUILD
            Debug.Log($"Finalizer -> {typeof(T)}");
#endif
        }

        public void Dispose()
        {
            Dispose(disposing: true);
            GC.SuppressFinalize(this);
        }
    }
}

在外部 dll 中添加此 TestProcess 类,并调用 TestProcess.Main()

using Com.Test;
using UnityEngine;

namespace Com.ExternalPackage
{
    public static class TestProcess
    {
        public static void Main()  // 在外部 dll 中调用此过程
        {
            int len = 8;
            using (var o = new SampleDisposableClass<int>(len))
            {
                using (var p = new SampleDisposableClass<float>(len))
                {
                    for (int i = 0; i < len; i++)
                    {
                        o[i] = i;
                        p[i] = o[i] * 0.5f;
                    }
                    Debug.Log(p[len - 1]);
                }
            }
        }
    }
}

将观察到外层的 SampleDisposableClass<int> 实例没有正确调用 Dispose()。期待的行为是所有构造的 SampleDisposableClass<T> 实例都应该正确调用 Dispose()

UnityEngine:2020.3.13f1c1

ILRuntime:2.0.2

@liiir1985
Copy link
Collaborator

image
无法重现

@liiir1985
Copy link
Collaborator

已修复

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants