NullReferenceException with no stack trace when hooking SetConsoleCtrlHandler

后端 未结 2 1950
甜味超标
甜味超标 2020-12-20 18:58

Using code to hook the console close event from this thread, I sometimes get a NullReferenceException with no stacktrace (most of the times I don\'t). It happen

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-20 19:24

    The most typical issue with code like that is not keeping a reference to the delegate instance. The one you pass as the first argument to SetConsoleCtrlHandler(). The garbage collector cannot see references held to a delegate object by unmanaged code. So this will, eventually, bomb when the garbage collector runs:

     SetConsoleCtrlHandler(Handler, true);
    

    which is the exact same thing as

     SetConsoleCtrlHandler(new EventHandler(Handler), true);
    

    assuming you used the types in the linked code. The author of that code carefully avoided this issue by making _handler a static variable. As opposed to the temporary delegate instance that is created by the previous two lines of code. Storing it in a static variable ensures it stays referenced for the life of the program. The Right Thing to do in this particular case since you are actually interested in the events until the program ends.

提交回复
热议问题