关于“A Native Collection has not been disposed, resulting in a memory leak. Enabl”问题

项目场景:

提示:这里简述项目相关背景:

例如:当在进行UnityWebRequest请求数据时候,打印就报错显示“A Native Collection has not been disposed, resulting in a memory leak. Enabl”,但不能定位错误的地方在哪,于是百度也没有明确答案,然后摸索一番,后面是老大告诉我的,记录一下;


问题描述

提示:这里描述项目中遇到的问题:

例如:数据请求提交过程中,UnityWebRequest 不时出现数据没有释放的情况,偶尔会一部分数据
内存溢出情况:

IEnumerator Post(string url, string data, Action<string, bool> callback)
{
    
    
        UnityWebRequest post = UnityWebRequest.Post(url, "POST");
        if (!string.IsNullOrEmpty(data))
        {
    
    
            post.uploadHandler = (UploadHandler)new UploadHandlerRaw(Encoding.UTF8.GetBytes(data));
        }
        post.SetRequestHeader("Content-Type", "application/json");//根据个API需求定义请求头
        yield return post.SendWebRequest();
        if (post.result == UnityWebRequest.Result.Success)
        {
    
    
            callback?.Invoke(post.downloadHandler.text, true);

        }
        else
        {
    
    
            callback?.Invoke(post.error, false);
            Debug.LogError($"{
      
      post.error}:{
      
      transform}");
        }
}

原因分析:

提示:这里填写问题的分析:

这个通常都是直接使用了Nativearray过时没有释放就会报这个错
使用NativeArray的时候最好前面加 Using,或者结束时显示释放

Using(){
    
    
.....
}

显式释放


解决方案:

提示:这里填写该问题的具体解决方案:

在代码块前面加上using

IEnumerator Post(string url, string data, Action<string, bool> callback)
{
    
    
        using UnityWebRequest post = UnityWebRequest.Post(url, "POST");
        if (!string.IsNullOrEmpty(data))
        {
    
    
            post.uploadHandler = (UploadHandler)new UploadHandlerRaw(Encoding.UTF8.GetBytes(data));
        }
        post.SetRequestHeader("Content-Type", "application/json");//根据个API需求定义请求头
        yield return post.SendWebRequest();
        if (post.result == UnityWebRequest.Result.Success)
        {
    
    
            callback?.Invoke(post.downloadHandler.text, true);

        }
        else
        {
    
    
            callback?.Invoke(post.error, false);
            Debug.LogError($"{post.error}:{transform}");
        }
}

这样貌似就没有显示过了,除了这请求地方,其他地方还需要注意一下,目前只发现这个地方会有类似情况,有什么错误的,还希望各位大佬指出一下。

猜你喜欢

转载自blog.csdn.net/qq_15355867/article/details/128558955