Skip to content

Help me understand SerializeUnsafe #209

@juho-hanhimaki

Description

@juho-hanhimaki

What is safe way to use the SerializeUnsafe?

Is for example following absolutely safe thing to do even in multithreaded scenario:

            var unsafeBuffer = MessagePackSerializer.SerializeUnsafe(foo);

            // simulate some work done on this same thread.
            //some other thread may use the MessagePackSerializer while this is going on.
            // is it safe to use unsafeBuffer later in this same thread?
            System.Threading.Thread.Sleep(1000);

            var safeBuffer = ArrayPool<byte>.Shared.Rent(unsafeBuffer.Count);
            try
            {
                unsafeBuffer.CopyTo(safeBuffer);
                // use the safe buffer...
            }
            finally
            {
                // after safe buffer is no more needed return it to pool
                ArrayPool<byte>.Shared.Return(safeBuffer);
            }

My motivation is to avoid allocating new buffers all the time and instead use pooled buffers.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions