简体   繁体   中英

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?

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM