Home > OS >  Xamarin/Maui Android, Task.Delay().ContinueWith, DisplayAlert not fired
Xamarin/Maui Android, Task.Delay().ContinueWith, DisplayAlert not fired

Time:08-03

I have this code, but Display alert never fired, can't understand - why so?

await Task.Delay(_doublePressTimeout - _buttonReleaseTimeout)
    .ContinueWith(async c =>
    {
        if (pushed != Constants.Direction.Empty)
        {
            await Shell.Current.DisplayAlert("qwe", pushed.ToString(), "OK");
        }
    });

But works this way:

await Task.Delay(_doublePressTimeout - _buttonReleaseTimeout);
if (pushed != Constants.Direction.Empty)
{
    await Shell.Current.DisplayAlert("qwe", pushed.ToString()   " begin", "OK");
}

WHY?

CodePudding user response:

Tasks have an implicit .ConfigureAwait(true) when they're awaited straight up, which is why you have a warning to state it explicitly (or even better, use .ConfigureAwait(false) selectively for large performance increases where applicable).

.ContinueWith can also capture the context and/or schedule the continuation on specific threads, which you should be doing for UI access, but you need to call the overload with the parameters for it.

That said, you'll be hard pressed to find a valid use case for .ContinueWith over just task awaiting. As you can see from your own example, it's easy to translate broken .ContinueWith to correct (and simpler) await Task code.

CodePudding user response:

This could be useful. The execution could be happening before the delay is done as not being awaited? The answer from the question may be applied here as well

  • Related