Closed xiaomi7732 closed 1 year ago
Notes:
LazyLazy<Func<CancellationToken, Task>>
, and then, it starts to look like an AsyncLazy library - that feels a bit heavy for this case; It is also an intention not to own tricky implementations in this library.
Use an AsyncLazy library - don't need to worry about owning the complex logic. I went over some open-source libraries, and most of them are more than just AsyncLazy, and not all libraries are always dealing with all the issues. It is doable, it is probably not worth introducing the dependency for this scenario.
Going back to the origin of the issue - do not run the code 2nd time, and a stupidly simple solution would be: Have a ref counter, start at 0, and drop the execution when it is increased to 1. Here's a pseudo:
int _refCount = 0;
async Task ExecuteAsync(CancenllationToken cancellationToken)
{
if ( refCount >= 1 ) { return; } // Already executed;
Interlocked.Increment(ref refCount);
if ( refCount != 1 ) { return; } // Only thread got refCount == 1 survives.
// Start to run the logic. No cancellation token passing around.
}
I am currently leaning toward 3. I think it is simple enough and easy to understand the semantics, and it doesn't have additional dependencies and is lightweight.
Another approach suggested by @karol-ms: just take a lock, considering this isn't any hot path
static readonly _lock = new object();
bool _executed;
async Task ExecuteAsync(CancenllationToken cancellationToken)
{
lock(_lock)
{
if (_executed) { return; } // Already executed.
_executed = true;
}
// The rest of the code.
}
A consideration: use a Task
Tag @karolz-ms. He initiated the idea.
In the current implementation, it is undesire to call
StartApplicationInsightsKubernetesEnricher()
when hosted services exist, because it leads to duplicated call into ExecuteAsync - 1 from the background service, 1 from the explicit call of the method above.Look into how to make
ExecuteAsync()
idempotent or find out a way to allowExecuteAsync()
to be called multiple times - that will reduce the chance for client code to callStartApplicationInsightsKubernetesEnricher()
by accident, and become more refactor friendly.