| | | 1 | | using Elsa.Extensions; |
| | | 2 | | |
| | | 3 | | namespace Elsa.Workflows.Runtime; |
| | | 4 | | |
| | | 5 | | /// <summary> |
| | | 6 | | /// Provides a set of extension methods for working with deferred tasks within a workflow execution context. |
| | | 7 | | /// </summary> |
| | | 8 | | public static class DeferredTasksExecutionContextExtensions |
| | | 9 | | { |
| | 3 | 10 | | private static readonly object DeferredTasksKey = new(); |
| | | 11 | | |
| | | 12 | | /// <summary> |
| | | 13 | | /// Defers the execution of a task within the workflow execution context. |
| | | 14 | | /// Deferred tasks are executed right after bookmarks have been persisted. |
| | | 15 | | /// </summary> |
| | | 16 | | public static void DeferTask(this WorkflowExecutionContext context, Func<Task> task) |
| | | 17 | | { |
| | 3 | 18 | | var deferredTasks = context.GetDeferredTasksInternal(); |
| | 3 | 19 | | deferredTasks.Add(task); |
| | 3 | 20 | | } |
| | | 21 | | |
| | | 22 | | /// <summary> |
| | | 23 | | /// Defers the execution of a task within the workflow execution context. |
| | | 24 | | /// Deferred tasks are executed right after bookmarks have been persisted. |
| | | 25 | | /// </summary> |
| | | 26 | | public static void DeferTask(this ActivityExecutionContext context, Action task) |
| | | 27 | | { |
| | 0 | 28 | | context.DeferTask(() => |
| | 0 | 29 | | { |
| | 0 | 30 | | task(); |
| | 0 | 31 | | return Task.CompletedTask; |
| | 0 | 32 | | }); |
| | 0 | 33 | | } |
| | | 34 | | |
| | | 35 | | /// <summary> |
| | | 36 | | /// Defers the execution of a task within the workflow execution context. |
| | | 37 | | /// Deferred tasks are executed right after bookmarks have been persisted. |
| | | 38 | | /// </summary> |
| | | 39 | | public static void DeferTask(this ActivityExecutionContext context, Func<Task> task) |
| | | 40 | | { |
| | 3 | 41 | | context.WorkflowExecutionContext.DeferTask(task); |
| | 3 | 42 | | } |
| | | 43 | | |
| | | 44 | | /// <summary> |
| | | 45 | | /// Executes all deferred tasks within the workflow execution context. |
| | | 46 | | /// </summary> |
| | | 47 | | public static async Task ExecuteDeferredTasksAsync(this WorkflowExecutionContext context) |
| | | 48 | | { |
| | 466 | 49 | | var deferredTasks = context.GetDeferredTasksInternal(); |
| | 469 | 50 | | var tasks = deferredTasks.Select(x => x()).ToList(); |
| | 466 | 51 | | await Task.WhenAll(tasks); |
| | 466 | 52 | | } |
| | | 53 | | |
| | | 54 | | private static ICollection<Func<Task>> GetDeferredTasksInternal(this WorkflowExecutionContext context) |
| | | 55 | | { |
| | 935 | 56 | | return context.TransientProperties.GetOrAdd(DeferredTasksKey, () => new List<Func<Task>>()); |
| | | 57 | | } |
| | | 58 | | } |