I'm having trouble with the below code. The async void
method is a handler for an event in another part of my code, so the event invocation arrives here and this code can asynchronously handle it.
I am attempting to have runningTask
represent the long-running stuff that may be happening in the background already. But the below shows that my understanding is off, as when I attempt to assign a value to runningTask
, it immediately invokes the method.
The desired behavior is to assign HandleAsync()
to runningTask
, and then await it's long-running result. But the assignment is a method therefore immediately starts executing the method. I need to assign runningTask
something to do (aka the logic inside of HandleAsync()
), and then once assigned, execute that logic at the await
statement. Can you demonstrate how to refactor this (and fix my incorrect understanding of how to express this)
static XDocument document{get;set;}
static ConcurrentQueue<Args> backlog = new ConcurrentQueue<Args>();
static Task runningTask {get;set;}
static async Task HandleAsync(XDocument document, Args e, CancellationToken token)
{
// await a long-running XML doc modification
// await a long running file write
}
static async void Event_Invoked(Args e)
{
if (runningTask is Task t && t.Status == TaskStatus.Running)
{
backlog.Enqueue(e);
return;
}
//This assignment is an invocation of the method.
runningTask = HandleAsync(document, e,tokenSource.Token);
await runningTask.ConfigureAwait(false);
}