Ingweland
Ingweland

Reputation: 1077

Is execution of async Task and async void same

Code examples will use Xamarin Android.

I am extending the IntentService. It has few lifecycle methods. In particular, void OnHandleIntent(Intent intent) where you do actual work, and void OnDestroy() which is called by the system when it sees that the service finished working and it's time to destroy it. For IntentService, the end of its life is when OnHandleIntent returns.

Being an event-like method, it's OK to use async void OnHandleIntent. Consider following code

protected override async void OnHandleIntent(Intent intent)
{
    Debug.Out("OnHandleIntent Start");
    await Task.Run(async () => await Task.Delay(1000));
    Debug.Out("OnHandleIntent End");
}

protected override void OnDestroy(Intent intent)
{
    base.OnDestroy();
    Debug.Out("OnDestroy");
}

The output is:

Debug.Out("OnHandleIntent Start");
Debug.Out("OnDestroy");
Debug.Out("OnHandleIntent End");

At the same time, following (blocking) code works as expected

protected override void OnHandleIntent(Intent intent)
{
    Debug.Out("OnHandleIntent Start");
    Task.Run(async () => await Task.Delay(1000)).Wait();
    Debug.Out("OnHandleIntent End");
}

protected override void OnDestroy(Intent intent)
{
    base.OnDestroy();
    Debug.Out("OnDestroy");
}

The output is:

Debug.Out("OnHandleIntent Start");
Debug.Out("OnHandleIntent End");
Debug.Out("OnDestroy");

The question is - why does it happens?

Upvotes: 0

Views: 65

Answers (1)

tmaj
tmaj

Reputation: 35105

async void methods cannot be awaited by the caller (because no Task is returned to wait for).

The first implementation will return before Delay is done; it will be executed as a fire and forget operation.


Btw.

await Task.Run(async () => await Task.Delay(1000))

can be

await Task.Delay(1000))

Upvotes: 1

Related Questions