Are static variables thread-safe? C#

后端 未结 7 1578
南笙
南笙 2020-12-03 00:35

I want to create a class which stores DataTables, this will prevent my application to import a list of details each time I want to retrieve it. Therefore this should be done

相关标签:
7条回答
  • 2020-12-03 01:32

    I think you should be fine. There is a liight chance that 2 threads will determine that the datatable is null and both read the table, but only one gets to assign the unitTable / currencyTable reference last, so worst case you be initalizing them more than once. But once they're set I think you'd be good. AS LONG AS YOU DON'T WRITE TO THEM. Theat could leave one in an inconsistent state.

    If you want to avoid the double init you could wrap the whole getter code in a lock statement. It's a lot like initializing a singleton.

    Also add a method that let's you set the references to null again so you can force a refresh.

    GJ

    0 讨论(0)
提交回复
热议问题