TomTom
TomTom

Reputation: 62093

Async method waiting for end?

I am rewriting some of my component management to use async start methods. Sadly it looks like a call to an async method WITHOUT await, still does await the result?

Can anyone enlighten me?

I am calling:

public async Task StartAsync() {
    await DoStartProcessingAsync();
}

which in itself is calling a slow implementation of protected abstract Task DoStartProcessingAsync(); - slow because it dome some EF calls, then creates an appdomain etc. - takes "ages".

The actual call is done in the form:

x.StartAsync().Forget();

with "Forget" being a dummy function just to avoid the "no await" warning:

public static void Forget(this Task task) {
}

Sadly, this sequence - is waiting for the slow DoStartAsync method to complete, and I see no reason for that. I am quite old in C#, but quite new to async/await and I was under the impression that, unless I await for the async task - the method would complete. As such, I expected the call to StartAsyc().Forget() to return immediatly. INSTEAD stack trace shows the thread going all the way into the DoStartProcessingAsync() method without any async processing happening.

Anyone can enlighten me on my mistake?

Upvotes: 2

Views: 1784

Answers (1)

Liam
Liam

Reputation: 29664

What your trying to achieve here is a fire and forget type mechanism. So async/await isn't really what you want. Your not wanting to await anything.

These are designed to free up threads for long running processes. Right now your returning a Task using an await and then "forgetting" it. So why return the Task at all?

Your freeing up the thread for the long running process, but your also queuing a process that ultimately does nothing (this is adding overhead that you could likely do without).

Simply doing this, would probably make more sense:

public void StartAsync() {
    Task.Run(() => DoStartProcessingAsync());
}

One thing to bear in mind is that your now using a ThreadPool thread not a UI thread (depending on what is actually calling this).

Upvotes: 3

Related Questions