View on GitHub

SARAFF SOFTWARE

All products / Saraff.TwainX.Extensions

Asynchronous Acquisition

XDs.AcquireAsync exposes the asynchronous acquisition API of Saraff.TwainX 1.0.35 through the typed XDs model. It runs a complete acquisition on a dedicated session thread, returns all pages as streams, supports progress and cancellation, and never blocks the calling thread.

public Task<TwainXAcquisitionResult> AcquireAsync(
    TwainXAcquireOptions options = null,
    Action<XCapabilitySession> configure = null,
    CancellationToken cancellationToken = default);

The method creates a TwainXAcquisitionSession for the call. The session owns a private TwainX instance, its own DSM connection and its own thread. The XDsm instance only serializes and coordinates the calls; it does not reuse its synchronous TwainX session for the async path.

Options

TwainXAcquireOptions comes from Saraff.TwainX:

Property Default Meaning
ShowUI false Show the data source UI
ModalUI false Use a modal source UI
Parent IntPtr.Zero Parent window handle for the source UI
DsmPath null Explicit DSM path
MaxImages null (unlimited) Stop after N pages; must be positive
DisableAfterAcquire true Disable the source after acquisition
Progress null IProgress<TwainXAcquisitionProgress> callback

If options is null, the extensions use ShowUI from the XDsm factory and leave the other options at their defaults. The language and country passed to XDsm.Create(...) are not copied to the async session. Set Parent in the options for a UI application.

var options = new TwainXAcquireOptions
{
    ShowUI = true,
    ModalUI = false,
    Parent = parentHandle,
    MaxImages = 1,
    DisableAfterAcquire = true,
    Progress = new Progress<TwainXAcquisitionProgress>(p =>
        Console.WriteLine($"Page {p.PageNumber}: {p.ImageInfo.ImageWidth}x{p.ImageInfo.ImageLength}"))
};

Progress is reported on the acquisition thread. Progress<T> captures the synchronization context of the thread that created it, which is usually what a UI application wants.

Source selection

XDsm.AcquireAsync performs these steps on the session thread:

  1. create TwainXAcquisitionSession with the options;
  2. open the DSM and the default data source;
  3. if the selected XDs index differs from the opened source, close it, set TwainX.SourceIndex and open the selected source;
  4. invoke the configure callback;
  5. call TwainX.Acquire().

The configure callback therefore runs with the correct source already open:

using (var result = await source.AcquireAsync(
    options,
    session =>
    {
        session.GetCapability<float>(TwCap.XResolution).Set(300f);
        session.GetCapability<float>(TwCap.YResolution).Set(300f);
        session.GetCapability<TwPixelType>(TwCap.IPixelType).Set(TwPixelType.RGB);
    },
    cancellationToken))
{
    // consume result.Streams
}

Use XCapabilitySession only inside the callback. It exposes GetCapability<T>, IsCapSupported and the private TwainX instance. Do not use XDs.TwainX or synchronous transfer helpers from the callback.

For session-bound capabilities, XCapability<T>.DataSource is null. The capability still supports Set, Reset, Values and IsSupported, but those operations must run on the session thread, which is guaranteed inside the callback.

Result

TwainXAcquisitionResult contains the pages captured during the acquisition:

Member Description
IReadOnlyList<Stream> Streams One memory stream per page
IReadOnlyList<TwainX.ImageInfo> ImageInfos One ImageInfo per page
Dispose() Disposes all streams and clears the lists

The streams are copies created from the session’s EndXfer data and remain valid after the TWAIN session is closed. The caller owns the result and its streams:

using (var result = await source.AcquireAsync(options, configure, cancellationToken))
{
    for (var i = 0; i < result.Streams.Count; i++)
    {
        using (var file = File.Create($"scan-{i}.png"))
        {
            result.Streams[i].CopyTo(file);
        }
    }
}

Disposing the result disposes every stream. If the application keeps a stream, it must copy or detach it before the result is disposed.

Cancellation

The token is linked with the XDsm lifetime token. Cancellation is cooperative and is checked by the base session while it waits for TWAIN events. A cancelled acquisition throws OperationCanceledException (usually TaskCanceledException) and disposes the partial result streams internally.

using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(5));

try
{
    using var result = await source.AcquireAsync(options, configure, cts.Token);
    // use result
}
catch (OperationCanceledException)
{
    Console.WriteLine("Acquisition cancelled.");
}

XDsm.Dispose() cancels the XDsm lifetime token, so an in-flight async acquisition is cancelled when the manager is disposed. New async calls after disposal throw ObjectDisposedException.

Concurrency

Situation Behavior
Two AcquireAsync calls on the same XDsm Serialized by a per-manager semaphore; the second waits
Async call while a synchronous transfer is active InvalidOperationException
Synchronous transfer while an async call is active InvalidOperationException
Different XDsm instances Not coordinated by the extensions; the TWAIN DSM is process-wide, so serialize if needed

The async path is intentionally independent of the synchronous TwainX session. It does not share capability state with XDs.TwainX.

Limitations

When to use the async API

Use XDs.AcquireAsync when:

Use the synchronous transfer helpers when the application already owns a TwainX session and needs native, memory-file or disk-file transfer, or when it must integrate with an existing UI thread and message loop.