Is there a race condition in this common pattern used to prevent NullReferenceException?

前端 未结 2 667
我在风中等你
我在风中等你 2020-12-15 17:46

I asked this question and got this interesting (and a little disconcerting) answer.

Daniel states in his answer (unless I\'m readin

2条回答
  •  无人及你
    2020-12-15 18:03

    This code will not throw a null reference exception. This one is thread safe:

    public void DoCallback() {
        Action local;
        local = Callback;
        if (local == null)
            local = new Action(() => { });
        local();
    }
    

    The reason this one is thread-safe, and can-not throw a NullReferenceException on Callback, is it's copying to a local variable before doing it's null check / call. Even if the original Callback was set to null after the null check, the local variable will still be valid.

    However the following is a different story:

    public void DoCallbackIfElse() {
        if (null != Callback) Callback();
        else new Action(() => { })();
    }
    

    In this one it's looking at a public variable, Callback can be changed to null AFTER the if (null != Callback) which would throw an exception on Callback();

提交回复
热议问题