Search code examples
c#xamarineventhandlerunreachable-code

Unreachable Code Warning in Static EventHandler callback


We have an interesting issue occurring that I wonder if anyone may be able to shed light on. We are currently seeing the warning: "Method never reaches end or 'return' statement" on an event handler delegate callback that is rather odd.

Consider the following code (you can ignore the SCB_ functions, they are not relevant to the question):

public static class NativeBridge
{
    private static UnityEventQueue _eventQueue;
    private static bool _initialized;

    public static void Init() 
    {
        if (_initialized)
        {
            return;
        }
        _initialized = true;
        SCB_SDKInit();
        _eventQueue = UnityEventQueue.Instance;
        _eventQueue.AppExiting += EventQueue_AppExiting;
        SCB_registerReceivedSistrCallback(SistrReceived);
    }

    //Lots of other irrelevant code

    private static void EventQueue_AppExiting(object sender, EventArgs e)
    {
        SCB_registerReceivedSistrCallback(null);
        _eventQueue.AppExiting -= EventQueue_AppExiting;
        SCB_SDKFinal();
        _initialized = false;
    }

}

The warning is on EventQueue_AppExiting. Here is the odd part. If I comment out the unregistration, _eventQueue.AppExiting -= EventQueue_AppExiting, the warning disappears.

We have tried a variety of "solutions" for what seems like a bug in the unreachability pass of the compiler:

  1. Make the static class, non-static and adjust accordingly
  2. Make the event in UnityEngineQueue static, and adjust accordingly
  3. Place the event un-registration at the end of the callback method
  4. Comment out the calls to the void SCB_ functions to sanity check
  5. Various other Spaghetti at the wall solutions

All of the above yielded no change in the compiler's behavior. Our best guess is that the compiler detects the unregistration and thinks that because the delegate is removed, that it cannot complete execution at runtime, even though I believe the stack would have to continue execution even after removal because the invocation had already begun.

It does not seem like this is having any adverse effect in the application's execution, however it is difficult to debug due to the nature of the event's invocation conditions (Application Exiting).

What could the complier be seeing and/or what are we potentially doing wrong?

P.S. For a bit of context, the class is static because it acts as an extern bridge to various platform specific libraries with a similar API. But that fact has little to do with the question, just to quell the "EWWWW Static Class" sentiment.


Solution

  • I think it is a bug as reported on this link:

    https://bugzilla.xamarin.com/show_bug.cgi?id=42819

    and here

    https://bugzilla.xamarin.com/show_bug.cgi?id=41798

    They report as fixed in version 6.2.0.259