Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice
  3. Dismiss Notice

Feedback Awaitables should not throw exceptions by default

Discussion in 'Unity 6 Beta' started by kdserra, Nov 1, 2023.

  1. kdserra

    kdserra

    Joined:
    May 16, 2018
    Posts:
    10
    The problem:
    Currently Awaitables throw exceptions when they are cancelled.

    This requires us to catch exceptions in order to cancel Awaitables which is a common thing to do in async workflows. This has performance drawbacks because exception handling is expensive and makes Awaitables less viable as a result.

    The current solution:
    In this thread it was said that the reason Awaitables throw by default is because:

    Quote from @simon-ferquel-unity
    """
    The problem with not raising the exception, is that it is totally unsafe, as the continuation will never run.
    Imagine something like the following:

    Code (CSharp):
    1. using(var someNativeResource = SomeApi.ReturningSomethingThatNeedsDispose()){
    2. await SomeAwaitableThatCanBeJustInterupted();
    3. }

    4. // or even worse with standard-ish use of SemaphoreSlim:

    5. await semaphoreSlim.WaitAsync();
    6. try{
    7. await SomeNonExceptionCancellableAsync();
    8. }
    9. finally{
    10. semaphoreSlim.Release();
    11. }
    In the first case, Dispose won't ever be called, which can be problematic in some scenarios.
    Second case, you will end up with a deadlock as the semaphore won't be released.
    """

    The proposed solution:

    The solution to this is an opt-in solution just like C# Tasks do
    CancellationToken.ThrowIfCancellationRequested

    This lets you throw exceptions in the edge cases where it's necessary, but comes without the performance drawbacks of catching exceptions where it's not needed and simple CancellationToken.IsCancellationRequested checks will suffice.
     
  2. Thygrrr

    Thygrrr

    Joined:
    Sep 23, 2013
    Posts:
    705
    Absolutely agree.

    And please add a onDisabledCancellationToken to Mono behaviour, not everyone wants to destroy their UI scene when a user clicks cancel on a download progress bar...
     
    SisusCo and kdserra like this.