DEV Community

Piler
Piler

Posted on

1

[Unity] UnityWebRequest: A Native Collection has not been disposed, resulting in a memory leak.

Issue: Use UnityWebRequest POST with JSON may cause the error below.

private IEnumerator PostWithJson(string url, string json)
{
    using (UnityWebRequest request = UnityWebRequest.Post(url, "POST"))
    {
        request.SetRequestHeader("Content-Type", "application/json");

        byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(json);
        using (UploadHandlerRaw uploadHandler = new UploadHandlerRaw(bodyRaw))
        {
            request.uploadHandler = uploadHandler;
            request.disposeUploadHandlerOnDispose = true;

            yield return request.SendWebRequest();

            if (request.result != UnityWebRequest.Result.Success)
            {
                Debug.Log(request.error);
            }
            else
            {
                Debug.Log(request.downloadHandler.text);
            }
            request.uploadHandler.Dispose();
            request.Dispose();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Solution: Use HttpWebRequest instead.

private string PostWithJson_CSharp(string url, string json)
{
    //Debug.Log($"url:{url}, json:{json}");
    try
    {
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Method = "POST";

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            streamWriter.Write(json);
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        Debug.Log(httpResponse.ProtocolVersion);
        using var streamReader = new StreamReader(httpResponse.GetResponseStream());
        var result = streamReader.ReadToEnd();
        return result;
    }
    catch (Exception e)
    {
        Debug.Log(e.Message);
        return null;
    };
}
Enter fullscreen mode Exit fullscreen mode

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay