Class SafeAtomicFileWriter
Thread-safe atomic file writer implementation using temporary files and file replacement.
Inherited Members
Namespace: Serenity.FilePersistence.Infrastructure.Services
Assembly: Serenity.IOFilePersistence.Infrastructure.dll
Syntax
public class SafeAtomicFileWriter : IFileWriterService, IService, IFoundationSettings
Remarks
This class ensures that file writes are atomic and thread-safe within the same process.
It uses a temporary file for writing and then replaces the target file to minimize the risk
of data corruption. It also handles concurrent writes to the same file path using a semaphore
per file path.
Constructors
SafeAtomicFileWriter(string, ILogService)
Constuctor for SafeAtomicFileWriter.
Declaration
public SafeAtomicFileWriter(string id, ILogService logService)
Parameters
| Type | Name | Description |
|---|---|---|
| string | id | |
| ILogService | logService |
Remarks
Initializes the internal state of the atomic file writer.
Properties
Guid
Declaration
public string Guid { get; set; }
Property Value
| Type | Description |
|---|---|
| string |
Id
Declaration
public string Id { get; set; }
Property Value
| Type | Description |
|---|---|
| string |
LogService
Declaration
public ILogService LogService { get; set; }
Property Value
| Type | Description |
|---|---|
| ILogService |
Methods
Write(string, ReadOnlySpan<byte>)
Write using a stream to a file atomically.
Declaration
public void Write(string path, ReadOnlySpan<byte> data)
Parameters
| Type | Name | Description |
|---|---|---|
| string | path | The file path to write to. |
| ReadOnlySpan<byte> | data | The data to write. |
Remarks
The stream will be disposed after writing.
WriteAsync(string, ReadOnlyMemory<byte>, CancellationToken)
Asynchronously write data to a file atomically.
Declaration
public Task WriteAsync(string path, ReadOnlyMemory<byte> data, CancellationToken cancellationToken)
Parameters
| Type | Name | Description |
|---|---|---|
| string | path | The file path to write to. |
| ReadOnlyMemory<byte> | data | The data to write. |
| CancellationToken | cancellationToken | Cancellation token to cancel the operation. |
Returns
| Type | Description |
|---|---|
| Task | A task representing the asynchronous write operation. |
WriteAtomic(string, byte[])
Write data to a file atomically.
Declaration
public void WriteAtomic(string path, byte[] data)
Parameters
| Type | Name | Description |
|---|---|---|
| string | path | The file path to write to. |
| byte[] | data | The data to write. |