Chilkat.Task Class Overview

Chilkat.Task represents an asynchronous Chilkat method call. A task is typically returned by a Chilkat method whose name ends in Async. The task can then be queued, monitored, waited on, canceled, and queried for its final result.

What the Class Is Used For

Use Chilkat.Task to manage asynchronous Chilkat operations. The task stores the method call and its arguments, runs on Chilkat's internal thread pool when started with Run, exposes status and progress information, and provides result methods such as GetResultBool, GetResultString, GetResultInt, and GetResultBytes.

Run Async Methods Queue an async method call with Run, or execute it synchronously with RunSynchronously.
Monitor Status Check Status, StatusInt, Live, Inert, and Finished.
Cancel Work Use Cancel to mark queued or running tasks for cancellation.
Read Results After completion, use ResultType and the matching result method to retrieve the return value.

Typical Workflow

  1. Call a Chilkat method ending in Async. It returns a Task object.
  2. Optionally set UserData or KeepProgressLog before starting the task.
  3. Call Run to queue the task on Chilkat's internal thread pool.
  4. Monitor Status, PercentDone, Live, or Finished.
  5. Optionally call Wait to wait for completion, with a timeout if desired.
  6. If cancellation is needed, call Cancel.
  7. After the task reaches a finished state, check Status, ResultType, TaskSuccess, and the appropriate result method.
  8. If the task failed, was aborted, or behaved unexpectedly, inspect ResultErrorText and LastErrorText.
Important result rule: If the underlying async method returns a boolean, use GetResultBool() to get the actual boolean result. TaskSuccess is mainly meaningful for async methods whose underlying synchronous method returns a non-boolean value.

Task Lifecycle

Status StatusInt Meaning State Group
empty 1 No method call and arguments are loaded into the task. This can occur only for an explicitly created task rather than one returned by an Async method. Inert
loaded 2 The method call and arguments are loaded, but the task has not yet been queued to run. Inert
queued 3 The task is waiting in the internal thread pool queue. Live
running 4 The task is currently running on a thread pool thread. Live
canceled 5 The task was canceled before entering the running state. Finished
aborted 6 The task was canceled while already running and later aborted. Finished
completed 7 The task completed. Whether the underlying method succeeded depends on the result value and method semantics. Finished
State helpers: Inert is true for empty or loaded. Live is true for queued or running. Finished is true for canceled, aborted, or completed.

Core Concepts

Concept Meaning Important Members
Loaded Task A task that contains an async method call but has not yet been started. Status, Inert
Queued Task A task waiting for a thread pool thread to become available. Run, Status, Live
Running Task A task currently executing in a background thread. PercentDone, Cancel, Live
Finished Task A task that completed, was canceled, or was aborted. Finished, ResultType, TaskSuccess
Progress Log An in-memory log of progress info events that can be examined while the task is running. KeepProgressLog, ProgressLogSize, ProgressInfoName, ProgressInfoValue
Result Retrieval After completion, the result is retrieved by calling the method that matches the result type. ResultType, GetResultBool, GetResultString, GetResultInt, GetResultBytes

Status and Identification Properties

Property Purpose Guidance
Status Text status of the task. Use for readable task state checks, logging, or debugging.
StatusInt Numeric status of the task. Use when code prefers integer comparisons.
Inert True if status is empty or loaded. Indicates the task has not yet been queued or started.
Live True if status is queued or running. Indicates the task is either waiting to run or currently running.
Finished True if status is canceled, aborted, or completed. Use to know when no more background work remains for the task.
TaskId Unique integer ID assigned to the task. Useful for identifying a task when a task-completion callback is used.
UserData Application-defined string attached to the task. Use to associate custom context with the task, especially when completion callbacks are used.

Running and Waiting

Method Behavior Use When
Run Queues the task to run on Chilkat's internal thread pool. Use for normal asynchronous execution after receiving a task from an Async method.
RunSynchronously Runs the task synchronously and returns after the task has run. Use when the task object should be executed without using background execution.
Wait Waits until the task completes, is canceled, is aborted, or until the timeout expires. Pass 0 to wait indefinitely. Returns false if the task was not started with Run or if the wait timeout expires.
SleepMs Sleeps the calling thread for the specified number of milliseconds. Useful when periodically polling task status. It does not sleep the task's background thread.
Wait callback note: HeartbeatMs controls AbortCheck callbacks for the Wait method. A background task running in a thread pool thread does not fire task events; the task's event callbacks pertain only to Wait.

Cancellation Behavior

Cancel marks a task for cancellation. The result depends on the task's current status.

Current Status Cancel Behavior Resulting Status
loaded Nothing is canceled because Run has not been called yet. Remains loaded
queued The task is marked for cancellation, dequeued, and will not run. canceled
running The running task is marked for cancellation. It will notice the cancellation flag and then abort. Eventually aborted, although it may become completed if cancellation happens just as it finishes.
canceled, aborted, or completed The task is already finished, so there is no change. No change
Cancellation is not instantaneous: If a task is already running, Cancel sets a flag that the background thread must notice. The task may still be running immediately after Cancel returns. Use Wait or poll Status until the task actually reaches a finished state.

Progress Monitoring

Property / Method Purpose Important Details
PercentDone Indicates percent completion while the task is running. Available only when the underlying operation can know progress as a percentage. The scale is determined by the async method object's PercentDoneScale property.
KeepProgressLog Enables an in-memory progress info log. Default is false. Set to true before running the task to keep progress log entries.
ProgressLogSize Number of progress log entries currently available. Only meaningful if KeepProgressLog is enabled.
ProgressInfoName Returns the name of the Nth progress info log entry. Indexing begins at 0.
ProgressInfoValue Returns the value of the Nth progress info log entry. Use with ProgressInfoName to inspect logged progress data.
RemoveProgressInfo Removes one progress log entry. Use to prune entries while the task is still running.
ClearProgressLog Removes all progress log entries. Use to empty the in-memory progress log.
Progress may be unavailable: Some operations cannot know percentage completion. For example, a TCP or TLS connection setup has no meaningful percentage, and an HTTP response using chunked transfer may not have a known total length.

Result Properties

Property Purpose Guidance
ResultType Indicates the data type of the task's result after completion. Possible values are bool, int, string, bytes, object, and void.
TaskSuccess Value of the LastMethodSuccess property of the underlying task object. Meaningful mainly when the underlying method returns a non-boolean value. If the method returns a boolean, use GetResultBool() instead.
ResultErrorText The LastErrorText for the task's asynchronous method. Check when the async method failed, was aborted, or produced unexpected results.
LastErrorText Diagnostic information for the last method or property access on the task object itself. Check after task-level method failures or unexpected behavior.

Retrieving Results

ResultType Use This Method Notes
bool GetResultBool Returns the boolean result of the underlying async method.
int GetResultInt Returns the integer result.
string GetResultString Returns the string result.
bytes GetResultBytes or CopyResultBytes GetResultBytes transfers the bytes to the caller. CopyResultBytes copies the bytes to the caller.
object Class-specific result loading method For object results, the relevant Chilkat class typically provides a method such as LoadTaskResult or LoadTaskCaller to load the completed task result.
void No value to retrieve Check task status and diagnostics as appropriate.
Retrieve results only after completion: ResultType and result methods are meaningful after the task has completed, canceled, or aborted. For successful results, wait until the task reaches completed.

Method Summary by Category

Category Methods / Properties Purpose
Run and wait Run, RunSynchronously, Wait, SleepMs Start the task, run it synchronously, wait for completion, or sleep while polling.
Cancel Cancel Mark a queued or running task for cancellation.
Status Status, StatusInt, Inert, Live, Finished Determine where the task is in its lifecycle.
Progress PercentDone, KeepProgressLog, ProgressLogSize, ProgressInfoName, ProgressInfoValue, RemoveProgressInfo, ClearProgressLog Monitor progress and inspect progress info log entries.
Results ResultType, TaskSuccess, GetResultBool, GetResultInt, GetResultString, GetResultBytes, CopyResultBytes Identify and retrieve the completed async method result.
Identification TaskId, UserData Associate a task with application-specific context or callback handling.
Diagnostics ResultErrorText, LastErrorText Read diagnostics for the underlying async method or task object.

Diagnostics and Troubleshooting

Problem Area Member What to Check
Task never starts Status, Run, LastErrorText Confirm the task is loaded and that Run was called successfully.
Wait returns false Wait The task may not have been started with Run, or the wait timeout may have expired.
Task was canceled before running Cancel, Status A queued task can be canceled before it reaches the running state, resulting in canceled.
Task is still running after Cancel Cancel, Status, Wait Cancellation is cooperative. The background thread needs time to notice the cancellation flag and abort.
Boolean result is misread TaskSuccess, GetResultBool If the underlying method returns a boolean, use GetResultBool rather than TaskSuccess.
Progress information is missing PercentDone, KeepProgressLog The operation may not be able to calculate percentage completion, or KeepProgressLog may not have been enabled before the task was run.
Need operation details after failure ResultErrorText, LastErrorText Use ResultErrorText for the underlying async method's LastErrorText. Use LastErrorText for task-level diagnostics.

Common Pitfalls

Pitfall Better Approach
Creating or receiving a task but forgetting to call Run. A loaded task does not execute until Run or RunSynchronously is called.
Assuming Cancel immediately stops a running task. Treat cancellation as cooperative. Wait or poll until the task reaches aborted, completed, or another finished state.
Using TaskSuccess for boolean-returning methods. Use GetResultBool() for the boolean return value of the underlying async method.
Expecting progress percentage to always be available. Some operations cannot know total work in advance, so PercentDone may not be meaningful.
Enabling progress logging after the task has already started. Set KeepProgressLog to true before calling Run.
Assuming the task background thread fires normal event callbacks. Task event callbacks pertain to the Wait method; the asynchronous task running in a background thread does not fire events.
Ignoring diagnostics after failed or aborted tasks. Check ResultErrorText and LastErrorText.

Best Practices

Recommendation Reason
Call Run soon after receiving an async task. Async method calls are loaded into the task, but do not execute until the task is started.
Use Finished, Live, and Inert for high-level state checks. They make lifecycle checks clearer than comparing every possible status string.
Use Wait with a finite timeout in responsive applications. It avoids blocking indefinitely while still allowing controlled waits.
Use UserData and TaskId when tracking multiple tasks. They help map completed tasks back to application-specific work items.
Set KeepProgressLog before running tasks that need progress inspection. Progress log entries are kept only when logging is enabled before execution.
Use ResultType to choose the correct result method. It prevents retrieving a result using the wrong method.
Check ResultErrorText after a failed, canceled, or aborted task. It contains the diagnostic text from the underlying asynchronous method.

Summary

Chilkat.Task is the control object for Chilkat asynchronous method calls. It stores the async method call, starts it with Run, tracks its lifecycle through statuses such as loaded, queued, running, canceled, aborted, and completed, and provides result and diagnostic access after the task finishes.

The most important practical guidance is to call Run to start the task, understand that cancellation is cooperative, use GetResultBool for boolean-returning methods, choose the correct result method based on ResultType, enable KeepProgressLog before running if progress details are needed, and inspect ResultErrorText when the underlying async operation fails.