Search Results for

Show / Hide Table of Contents

# Synchronous and asynchronous operations

Certain operations may take longer to execute. Such operations are available in both synchronous and asynchronous form. The synchronous form requires the client (i.e. your application) to wait for the end of the action; the call into memoQ Server does not return before the completion. The asynchronous operation queues the requested task, and then returns immediately with a task identifier. The task identifier can be used to poll the status of the task (i.e. if it is ready) and fetch the results of the task (if any).

Asynchronous operations are new in version 8.3. The operation names look like "Start...Task".

Asynchronous operations, where available, are favorable to synchronous operations.

Below is a code sample that demonstrates a typical asynchronous task lifecycle. After starting the operation the task shall be polled for status. Polling should not be too frequent (i.e. less frequent than once every few seconds), and it is recommended to batch multiple pending tasks to poll them together. (The code sample below does not show this batch polling.)

    void StatisticsAsyncTest()
    {
        // ... prepare project, add documents, etc
        IServerProjectService spService = getServerProjectService();
        // ... create options
        StatisticsOptions statOptions = new StatisticsOptions();
        // start async operation
        var statisticsTaskInfo = spService.StartStatisticsOnProjectTask(spGuid,
                                    null, statOptions, StatisticsResultFormat.Html);
        try
        {
            // register async task and poll for status
            var statisticsResult = waitForAsyncTaskToFinishAndGetResult(
                                statisticsTaskInfo.TaskId) as StatisticsTaskResult;
        }
        catch (Exception e) { ... }
    }

    private TaskResult waitForAsyncTaskToFinishAndGetResult(Guid TaskId)
    {
        ITasksService taskService = getTasksService();
        var taskStatus = taskService.GetTaskStatus(TaskId).Status;
        int i = 1;
        while (taskStatus != TasksService.TaskStatus.Cancelled
                    && taskStatus != TasksService.TaskStatus.Completed
                    && taskStatus != TasksService.TaskStatus.Failed
                    && taskStatus != TasksService.TaskStatus.InvalidTask)
        {
            if (i < 16)
                i = 2 * i;
            Thread.Sleep(i * 1000);
            taskStatus = taskService.GetTaskStatus(TaskId).Status;
        }
        if (taskStatus != TasksService.TaskStatus.Completed)
            thrownewException($"Task has status {taskStatus.ToString()}.");
        return taskService.GetTaskResult(TaskId);
    }