AsyncFile class
A file for asynchronous I/O through the core.
On this page
- Use
import ThinkMeta.ConcurrentTasks.AsyncIo.AsyncFile;- Namespace
ThinkMeta::ConcurrentTasks::AsyncIo- Platforms
- Windows, Linux
Syntax
class AsyncFileRemarks
On Windows the file is opened with FILE_FLAG_OVERLAPPED and associated with the core's I/O completion port; elsewhere its operations go to the core's io_uring (SubmitIo). Needs EnableAsyncIo (Core.h) before the first operation (on Windows before Create), and no operation may still be pending at DisableAsyncIo. All functions report errors as the platform's error code (Platform::ErrorCode: a Win32 error code on Windows, an errno elsewhere; 0 on success). Compare it through the names of Platform::Error (EndOfFile, TimedOut, OperationAborted, ...), which mean the same on every platform. Read, Write, ReadFile and WriteFile suspend the calling task while they wait, so call them from a task, or from an OS thread after ConvertThreadToTask. Completions run on the core's I/O thread (or on the calling thread when an operation completes at once on Windows). The object owns the file and closes it on destruction. Close or destroy it only when no operation is pending. The operations use no file pointer: every operation carries its offset.
See also
AsyncFileIoRequest, Platform::File
Methods
IsValid
Create
Opens or creates the file, on every platform alike.
Syntax
ErrorType Create(FileName fileName, const Platform::FileOptions& options) noexcept;Parameters
fileNameFileName- Path of the file; must not be
nullptr. optionsconst Platform::FileOptions&- How to open it.
Platform::FileOptions::unbufferedmakes the buffers, offsets and sizes of all transfers subject to sector alignment.
Return value
Type: ErrorType
0 if the file is open; otherwise the error, and no file is open.
Remarks
Precondition: no file is open. Does not suspend. On Windows the same as the overload with the flags of CreateFileW that the options stand for.
See also
Windows only
Opens or creates the file with the arguments of CreateFileW (Windows only).
Syntax
ErrorType Create(
FileName fileName,
DWORD access,
DWORD shareMode,
DWORD creationDisposition,
DWORD flagsAndAttributes
) noexcept;Parameters
fileNameFileName- Path of the file; must not be
nullptr. accessDWORD- Requested access:
GENERIC_READ,GENERIC_WRITEor both. shareModeDWORD- What other opens may do meanwhile:
0(exclusive) or a combination ofFILE_SHARE_READ,FILE_SHARE_WRITEandFILE_SHARE_DELETE. creationDispositionDWORDCREATE_NEW,CREATE_ALWAYS,OPEN_EXISTING,OPEN_ALWAYSorTRUNCATE_EXISTING.flagsAndAttributesDWORDFILE_ATTRIBUTE_*andFILE_FLAG_*values, e.g.FILE_FLAG_NO_BUFFERINGorFILE_FLAG_SEQUENTIAL_SCAN;FILE_FLAG_OVERLAPPEDis always added.
Return value
Type: ErrorType
ERROR_SUCCESS if the file is open and associated; otherwise the CreateFileW or association error, and no file is open.
Remarks
Calls CreateFileW with FILE_FLAG_OVERLAPPED added and associates the handle with the core's I/O completion port. Precondition: no file is open. Needs EnableAsyncIo. Does not suspend. The parameters go to CreateFileW unchanged (FILE_FLAG_NO_BUFFERING makes the buffers, offsets and sizes of all transfers subject to sector alignment). Returns the CreateFileW error, or the error of the association (AssociateHandleWithIoCompletionPort); if the association fails, the file is closed again, so after any error no file is open.
See also
Close
Closes the file (success if none is open). No operation may be pending.
Syntax
ErrorType Close() noexcept;Return value
Type: ErrorType
0 if the file was closed or none was open; otherwise the error of the close.
See also
GetSize
Gets the file size. Precondition: a file is open.
Syntax
ErrorType GetSize(FileSize& size) noexcept;Parameters
sizeFileSize&- Receives the file size in bytes; unchanged on failure.
Return value
Type: ErrorType
0, or the error of the call.
SetSize
Sets the file size. Precondition: a file is open.
Syntax
ErrorType SetSize(FileSize size) noexcept;Parameters
sizeFileSize- The new size in bytes; extending fills with zeros, shrinking cuts the file.
Return value
Type: ErrorType
0, or the error of the failed call.
Remarks
Needs no file pointer, so it also works on a file opened unbuffered for a size inside a sector. Only while no write is in flight.
ReadAsync
Starts an asynchronous read.
Syntax
ErrorType ReadAsync(
void* buffer,
ByteCount bytesToRead,
AsyncFileIoRequest& asyncIoRequest
) noexcept;Parameters
buffervoid*- Receives the data; at least
bytesToReadbytes, sector-aligned for a file opened unbuffered. bytesToReadByteCount- Maximum number of bytes to read.
asyncIoRequestAsyncFileIoRequest&- The request; its offset is the file position to read at.
Return value
Type: ErrorType
0: done at once, the request is already completed (on the calling thread; Windows only). Platform::Error::Pending: the request completes later on the I/O thread. Any other code: the read was not started and the request will not complete. Reading at or beyond the end of the file fails with Platform::Error::EndOfFile: on Windows possibly at once, elsewhere always through the completion.
Remarks
Never suspends. Set the offset (AsyncFileIoRequest::SetOffset, after AsyncFileIoRequest::Reset) before the call. buffer and the request belong to the caller and must stay valid and untouched until the request has completed. A completed read may be shorter than bytesToRead (end of file): check AsyncIoRequestBase::GetTransferredBytes.
See also
WriteAsync
Starts an asynchronous write.
Syntax
ErrorType WriteAsync(
const void* buffer,
ByteCount bytesToWrite,
AsyncFileIoRequest& asyncIoRequest
) noexcept;Parameters
bufferconst void*- The data to write; at least
bytesToWritebytes, sector-aligned for a file opened unbuffered. bytesToWriteByteCount- Number of bytes to write.
asyncIoRequestAsyncFileIoRequest&- The request; its offset is the file position to write at.
Return value
Type: ErrorType
As ReadAsync: 0 (completed at once), Platform::Error::Pending, or an error (not started).
Remarks
Never suspends. Ownership and lifetime of buffer and request as for ReadAsync.
See also
Read
Reads from the file and waits for the result.
Syntax
ErrorType Read(
void* buffer,
ByteCount bytesToRead,
ByteCount& bytesRead,
std::uint64_t filePosition,
Duration timeout = Duration::Infinite()
) noexcept;Parameters
buffervoid*- Receives the data; at least
bytesToReadbytes, sector-aligned for a file opened unbuffered. bytesToReadByteCount- Maximum number of bytes to read.
bytesReadByteCount&- Bytes read (less than bytesToRead at the end of the file);
0on error. filePositionstd::uint64_t- File offset in bytes to read at.
timeoutDurationDuration::Infinite: wait for the completion. Otherwise a read still pending after timeout is cancelled andPlatform::Error::TimedOutis returned, unless it completed meanwhile. A timeout needsEnableTimers; without it the wait has no limit.Default:Duration::Infinite()
Return value
Type: ErrorType
0 if the read completed; Platform::Error::TimedOut if it was cancelled after timeout; Platform::Error::OperationAborted if the task was cancelled (CancelTask); otherwise the error of the read (e.g. Platform::Error::EndOfFile).
Remarks
Suspends the calling task until the read has completed (also after a timeout, until the cancellation is through), so buffer may be reused as soon as it returns. A CancelTask of the calling task cancels a pending read like a timeout, also with Duration::Infinite. A read of a regular file may be past cancelling already; it then completes with its own result.
See also
Write
Writes to the file and waits for the result.
Syntax
ErrorType Write(
const void* buffer,
ByteCount bytesToWrite,
ByteCount& bytesWritten,
std::uint64_t filePosition,
Duration timeout = Duration::Infinite()
) noexcept;Parameters
bufferconst void*- The data to write; at least
bytesToWritebytes, sector-aligned for a file opened unbuffered. bytesToWriteByteCount- Number of bytes to write.
bytesWrittenByteCount&- Bytes written;
0on error. filePositionstd::uint64_t- File offset in bytes to write at.
timeoutDuration- As for
Read: a write still pending after timeout is cancelled and givesPlatform::Error::TimedOut.Default:Duration::Infinite()
Return value
Type: ErrorType
0 if the write completed; Platform::Error::TimedOut if it was cancelled after timeout; Platform::Error::OperationAborted if the task was cancelled (CancelTask); otherwise the error of the write.
Remarks
Suspends the calling task until the write has completed, and is cancelled, as Read is.
See also
ReadFile
Reads a whole file into sequential memory.
Syntax
static ErrorType ReadFile(
FileName fileName,
const Platform::FileOptions& fileOptions,
Memory::IWriteSequentialMemory* writeSequentialMemory,
const BulkIoOptions& options = {}
) noexcept;Parameters
fileNameFileName- Path of the file; must not be
nullptr. fileOptionsconst Platform::FileOptions&- How to open it, as for
Create; needs read access, usuallyPlatform::FileCreation::OpenExisting. Unbuffered, the memory's blocks andBulkIoOptions::blockSizemust be sector-aligned. The last block is then requested rounded up toBulkIoOptions::SectorAlign(the memory must have room for that) and released with the bytes the file still had. writeSequentialMemoryMemory::IWriteSequentialMemory*- Receives the file content; must not be
nullptr; borrowed, must outlive the call. optionsconst BulkIoOptions&- The shape of the I/O; reading starts at
BulkIoOptions::startOffset.Default:{}
Return value
Type: ErrorType
0 if the whole file was read; otherwise the first error (see remarks).
Remarks
Opens fileName (as Create does), reads it to the end into writeSequentialMemory with asynchronous requests in flight, and closes it. Suspends the calling task while it waits for reads (and possibly inside the memory's Memory::IWriteSequentialMemory::RequestWriteMemory). Needs EnableAsyncIo. The memory gets Memory::IWriteSequentialMemory::Initialize(bytes to read) first, then one RequestWriteMemory/Memory::IWriteSequentialMemory::ReleaseWriteMemory per block in file order, and always Memory::IWriteSequentialMemory::SetEndOfStream at the end - also on every error. If the file cannot be opened or sized, the memory gets an empty stream (Initialize(0)). Each finished block goes to the memory at once, so a consumer can start on the first blocks while the rest is on its way; a memory with a bounded window must hold at least BulkIoOptions::blocksInFlight blocks. The memory is borrowed: it must outlive the call. Returns the first error (open, size, Platform::Error::NotEnoughMemory for a nullptr block or the request array, a read's error, or Platform::Error::EndOfFile if a read came back short because the file shrank meanwhile); after an error no block is released to the memory any more, but the call still waits for every read in flight before it returns.
See also
Windows only
Reads a whole file into sequential memory; opened with the arguments of CreateFileW (Windows only).
Syntax
static ErrorType ReadFile(
FileName fileName,
DWORD access,
DWORD shareMode,
DWORD creationDisposition,
DWORD flagsAndAttributes,
Memory::IWriteSequentialMemory* writeSequentialMemory,
const BulkIoOptions& options = {}
) noexcept;Parameters
fileNameFileName- Path of the file; must not be
nullptr. accessDWORD- Requested access, as for
Create; must includeGENERIC_READ. shareModeDWORD- Share mode, as for
Create. creationDispositionDWORD- Creation disposition, as for
Create; usuallyOPEN_EXISTING. flagsAndAttributesDWORD- Flags and attributes, as for
Create;FILE_FLAG_NO_BUFFERINGreads unbuffered, asPlatform::FileOptions::unbuffereddoes. writeSequentialMemoryMemory::IWriteSequentialMemory*- Receives the file content; must not be
nullptr; borrowed, must outlive the call. optionsconst BulkIoOptions&- The shape of the I/O; reading starts at
BulkIoOptions::startOffset.Default:{}
Return value
Type: ErrorType
ERROR_SUCCESS if the whole file was read; otherwise the first error.
Remarks
Otherwise as the overload with Platform::FileOptions.
See also
WriteFile
Writes a whole file from sequential memory.
Syntax
static ErrorType WriteFile(
FileName fileName,
const Platform::FileOptions& fileOptions,
Memory::IReadSequentialMemory* readSequentialMemory,
const BulkIoOptions& options = {}
) noexcept;Parameters
fileNameFileName- Path of the file; must not be
nullptr. fileOptionsconst Platform::FileOptions&- How to open it, as for
Create; needs write access, usuallyPlatform::FileCreation::CreateAlways. Unbuffered, the memory's blocks andBulkIoOptions::blockSizemust be sector-aligned (BulkIoOptions::SectorAlign). A last block that is not is taken as the end of the data: it is written as whole sectors from a zero-padded copy, and the file is then cut to its exact size. readSequentialMemoryMemory::IReadSequentialMemory*- Supplies the data to write; must not be
nullptr; borrowed, must outlive the call. optionsconst BulkIoOptions&- The shape of the I/O;
BulkIoOptions::startOffsetis ignored, writing starts at offset0.Default:{}
Return value
Type: ErrorType
0 if all data was written; otherwise the first error (see remarks).
Remarks
Opens fileName (as Create does; use a creating option), writes the data of readSequentialMemory from offset 0 with asynchronous requests in flight, and closes it. Suspends the calling task while it waits for writes (and possibly inside the memory's Memory::IReadSequentialMemory::RequestReadMemory). Needs EnableAsyncIo. Blocks of up to options.BulkIoOptions::blockSize are taken with RequestReadMemory until it returns nullptr or 0 bytes (end of data); each is handed back with Memory::IReadSequentialMemory::ReleaseReadMemory(bytes written) once its write has completed, in order. The file is not truncated to the written size (with Platform::FileCreation::OpenExisting or Platform::FileCreation::OpenAlways older data beyond it stays), except unbuffered with a last block that is no multiple of BulkIoOptions::SectorAlign: then the file is cut to the written size. The memory is borrowed: it must outlive the call. Returns the first error (open, Platform::Error::NotEnoughMemory for the request array, or a write's error); after an error no new block is requested, but the call waits for every write in flight and still releases their blocks before it returns.
See also
Windows only
Writes a whole file from sequential memory; opened with the arguments of CreateFileW (Windows only).
Syntax
static ErrorType WriteFile(
FileName fileName,
DWORD access,
DWORD shareMode,
DWORD creationDisposition,
DWORD flagsAndAttributes,
Memory::IReadSequentialMemory* readSequentialMemory,
const BulkIoOptions& options = {}
) noexcept;Parameters
fileNameFileName- Path of the file; must not be
nullptr. accessDWORD- Requested access, as for
Create; must includeGENERIC_WRITE. shareModeDWORD- Share mode, as for
Create. creationDispositionDWORD- Creation disposition, as for
Create; usuallyCREATE_ALWAYS. flagsAndAttributesDWORD- Flags and attributes, as for
Create;FILE_FLAG_NO_BUFFERINGwrites unbuffered, asPlatform::FileOptions::unbuffereddoes. readSequentialMemoryMemory::IReadSequentialMemory*- Supplies the data to write; must not be
nullptr; borrowed, must outlive the call. optionsconst BulkIoOptions&- The shape of the I/O;
BulkIoOptions::startOffsetis ignored, writing starts at offset0.Default:{}
Return value
Type: ErrorType
ERROR_SUCCESS if all data was written; otherwise the first error.
Remarks
Otherwise as the overload with Platform::FileOptions.
See also
Types
ErrorType
FileName
FileSize
ByteCount
A byte count of one operation (DWORD on Windows, std::uint32_t elsewhere).
Syntax
using ByteCount = AsyncIoRequestBase::ByteCount;Generated from ThinkMeta.ConcurrentTasks.API @ c7663c4 (2026-11-19).