Is a string property itself threadsafe?

前端 未结 5 2112
一个人的身影
一个人的身影 2020-12-08 10:09

String\'s in C# are immutable and threadsafe. But what when you have a public getter property? Like this:

public String SampleProperty{
    get;
    private          


        
5条回答
  •  攒了一身酷
    2020-12-08 10:40

    Most of the answers are using the word "atomic" as if atomic changes are all that are needed. They're not, usually.

    This has been mentioned in the comments, but not usually in the answers - that's the only reason for me providing this answer. (The point about locking at a coarser granularity, to allow things like appending, is entirely valid as well.)

    Usually you want a reading thread to see the latest value of the variable/property. That isn't guaranteed by atomicity. As a quick example, here's a bad way to stop a thread:

    class BackgroundTaskDemo
    {
        private bool stopping = false;
    
        static void Main()
        {
            BackgroundTaskDemo demo = new BackgroundTaskDemo();
            new Thread(demo.DoWork).Start();
            Thread.Sleep(5000);
            demo.stopping = true;
        }
    
        static void DoWork()
        {
             while (!stopping)
             {
                   // Do something here
             }
        }
    }
    

    DoWork may well loop forever, despite the write to the boolean variable being atomic - there's nothing to stop the JIT from caching the value of stopping in DoWork. To fix this, you either need to lock, make the variable volatile or use an explicit memory barrier. This all applies to string properties as well.

提交回复
热议问题