Skip to content

SafeAction

Matheus Lessa Rodrigues edited this page Oct 28, 2017 · 1 revision

SafeAction

This is like System.Action but safer. When using System.Action with multiple callbacks, the callback chain is not stopped if one of the callbacks throws an exception. When using SafeAction, other callbacks are not affected. However, exceptions raised will not be rethrown (only logged in the console).

There are also generic versions available (up to two generic parameters).

Example

using UnityEngine;
using BitStrap;

public sealed class MyScript : MonoBehaviour
{
    public sealed class ExampleException : System.Exception {}

    private SafeAction<int> myAction = new SafeAction<int>();

    private void TestAction( int a )
    {
        Debug.LogFormat( "This is a test {0}", a );
    }

    private void TestActionWithException( int a )
    {
        throw new ExampleException();
    }

    private void Awake()
    {
        myAction.Register( TestActionWithException ); // Register first method that throws
        myAction.Register( TestAction ); // Register second method that logs to the console

        myAction.Call( 17 ); // Prints "This is a test 17"
                             // The callback chain is not stopped
    }
}
Clone this wiki locally