Closing a delegate without allocating memory

I wrote a helper class Thread, which you can use to execute a piece of code in the main Unity theme.

This is the blue print function:

public static void executeInUpdate(System.Action action)

The full script is really long and will make this post unnecessarily long. You can see the rest of the helper class script here .

Then I can use the join API from another Threadas follows:

UnityThread.executeInUpdate(() =>
{
    transform.Rotate(new Vector3(0f, 90f, 0f));
});

The problem is that when I use a variable declared outside this delegate, it allocates memory. The code above allocates 104 bytes in each frame. This is because of the variable transformthat is used inside this closure.

, 60 , 6 , . .

, Unity. 60 . receiveVideoFrame() . , Unity main Thread, Unity Texture2D. Texture2D RawImage. , - UnityThread.executeInUpdate.

bool doneUploading = false;
byte[] videoBytes = new byte[25000];
public Texture2D videoDisplay;

void receiveVideoFrame()
{
    while (true)
    {
        //Download Video Frame 
        downloadVideoFrameFromNetwork(videoBytes);

        //Display Video Frame 
        UnityThread.executeInUpdate(() =>
        {
            //Upload the videobytes to Texture to display
            videoDisplay.LoadImage(videoBytes);
            doneUploading = true;
        });

        //Wait until video is done uploading to Texture/Displayed
        while (!doneUploading)
        {
            Thread.Sleep(1);
        }

        //Done uploading Texture. Now set to false for the next run
        doneUploading = false;

        //Repeat again
    }
}

?

, ?

, , script, .

+4
1

, , Action Start Awake , โ€‹โ€‹ while.

, doneUploading a volatile, Threads . , lock boolean .

private volatile bool doneUploading = false;

byte[] videoBytes = new byte[25000];
public Texture2D videoDisplay;

Action chachedUploader;

void Start()
{
    chachedUploader = uploadToTexture;
}

void uploadToTexture()
{
    UnityThread.executeInUpdate(() =>
    {
        //Upload the videobytes to Texture to display
        videoDisplay.LoadImage(videoBytes);
        doneUploading = true;
    });
}

//running in another Thread
void receiveVideoFrame()
{
    while (true)
    {
        //Download Video Frame 
        downloadVideoFrameFromNetwork(videoBytes);

        //Display Video Frame (Called on main thread)
        UnityThread.executeInUpdate(chachedUploader);

        //Wait until video is done uploading to Texture/Displayed
        while (!doneUploading)
        {
            Thread.Sleep(1);
        }

        //Done uploading Texture. Now set to false for the next run
        doneUploading = false;

        //Repeat again
    }
}

, - - . , . .

+1

Source: https://habr.com/ru/post/1675426/


All Articles