Checking delegates for null

后端 未结 6 1997
滥情空心
滥情空心 2021-02-04 11:48

I was reading the Essential C# 3.0 book and am wondering if this is a good way to check delegates for null?:

class Thermostat
{
    public delegate void Temperat         


        
6条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-04 12:46

    If the Thermostat class doesn't need to be thread safe then yes the above code is fine - as long as there is only one thread accessing that instance of Thermostat there is no way for OnTemperatureChange to become unregistered between the test for null and the call to the event.

    If you need to make Thermostat thread safe then you might want to take a look at the following article (new to me, looks like a good read):

    http://www.yoda.arachsys.com/csharp/events.html

    For the record, the recommendation is that you develop your classes not to be thread safe unless thread safety is explicitly needed as it can significantly increase the complexity of your code.

提交回复
热议问题