private async Task ExecuteTaskAsync(TaskInfo taskInfo, CancellationToken cancellationToken) { EnsureArg.IsNotNull(taskInfo, nameof(taskInfo)); using ITask task = _taskFactory.Create(taskInfo); task.RunId = task.RunId ?? taskInfo.RunId; if (task == null) { _logger.LogWarning("Not supported task type: {taskTypeId}", taskInfo.TaskTypeId); return; } TaskResultData result = null; try { try { if (taskInfo.IsCanceled) { // For cancelled task, try to execute it for potential cleanup. task.Cancel(); } Task <TaskResultData> runningTask = Task.Run(() => task.ExecuteAsync()); _activeTaskRecordsForKeepAlive[taskInfo.TaskId] = task; result = await runningTask; } catch (RetriableTaskException ex) { _logger.LogError(ex, "Task {taskId} failed with retriable exception.", taskInfo.TaskId); try { await _consumer.ResetAsync(taskInfo.TaskId, new TaskResultData(TaskResult.Fail, ex.Message), taskInfo.RunId, cancellationToken); } catch (Exception resetEx) { _logger.LogError(resetEx, "Task {taskId} failed to reset.", taskInfo.TaskId); } // Not complete the task for retriable exception. return; } catch (Exception ex) { _logger.LogError(ex, "Task {taskId} failed.", taskInfo.TaskId); result = new TaskResultData(TaskResult.Fail, ex.Message); } try { await _consumer.CompleteAsync(taskInfo.TaskId, result, task.RunId, cancellationToken); _logger.LogInformation("Task {taskId} completed.", taskInfo.TaskId); } catch (Exception completeEx) { _logger.LogError(completeEx, "Task {taskId} failed to complete.", taskInfo.TaskId); } } finally { _activeTaskRecordsForKeepAlive.Remove(taskInfo.TaskId, out _); } }