-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtaskstatus.cs
106 lines (93 loc) · 3.13 KB
/
taskstatus.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
public class LazyAsyncFunctionStore
{
private class TaskInfo
{
public Func<Task> Function { get; }
public SemaphoreSlim Lock { get; } = new(1, 1); // Prevent multiple execution
public TaskInfo(Func<Task> function)
{
Function = function;
}
}
private readonly Lazy<Task<ConcurrentDictionary<string, TaskInfo>>> _lazyFunctions;
public LazyAsyncFunctionStore()
{
_lazyFunctions = new Lazy<Task<ConcurrentDictionary<string, TaskInfo>>>(InitializeAsync);
}
private async Task<ConcurrentDictionary<string, TaskInfo>> InitializeAsync()
{
await Task.Yield(); // Simulating async initialization
return new ConcurrentDictionary<string, TaskInfo>();
}
// Add a function safely
public async Task<bool> AddFunctionAsync(string key, Func<Task> function)
{
if (string.IsNullOrWhiteSpace(key) || function is null)
throw new ArgumentNullException(nameof(key), "Key or function cannot be null");
var dictionary = await _lazyFunctions.Value.ConfigureAwait(false);
return dictionary.TryAdd(key, new TaskInfo(function));
}
// Attempt to remove a function, but only if it's not running
public async Task<bool> RemoveFunctionAsync(string key)
{
if (string.IsNullOrWhiteSpace(key))
throw new ArgumentNullException(nameof(key), "Key cannot be null or empty");
var dictionary = await _lazyFunctions.Value.ConfigureAwait(false);
if (dictionary.TryGetValue(key, out var taskInfo))
{
// Ensure the function is not running
if (await taskInfo.Lock.WaitAsync(0))
{
try
{
return dictionary.TryRemove(key, out _);
}
finally
{
taskInfo.Lock.Release();
}
}
else
{
Console.WriteLine($"Cannot remove {key} as it is currently running.");
return false;
}
}
return false;
}
// Execute a function asynchronously
public async Task ExecuteFunctionAsync(string key)
{
var dictionary = await _lazyFunctions.Value.ConfigureAwait(false);
if (dictionary.TryGetValue(key, out var taskInfo))
{
if (await taskInfo.Lock.WaitAsync(0)) // Prevent multiple executions
{
try
{
await taskInfo.Function();
}
catch (Exception ex)
{
Console.WriteLine($"Error executing function {key}: {ex.Message}");
}
finally
{
taskInfo.Lock.Release();
}
}
else
{
Console.WriteLine($"Task {key} is already running.");
}
}
else
{
Console.WriteLine($"Function with key '{key}' not found.");
}
}
}