locked
.NET Optimization Policy RRS feed

  • Question

  • I have a following code
    class Test
    {
    bool IsDataProcessed = false;
    public void ProcessData()
    {
    getDataFromDatabase();
    IsDataProcessed = true;
    }
    public MyData getDataFromDatabase()
    {
    
    }
    }
    
     Are there any chances that due to processor optimization or compiler optimization being applied, IsDataProcessed = true is executed before getDataFromDatabase() in the function ProcessData()?

    Bhavesh
    • Changed type Mike Danes Sunday, July 31, 2011 10:38 PM
    Thursday, July 28, 2011 4:47 PM

Answers

  • It may happens due to either compiler/JIT optimization or CPU reordering.

     

    to prevent it, try MemoryBarrier, which disable it and caching in registers.

    Thread.MemoryBarrier();
    getDataFromDatabase();
    Thread.MemoryBarrier();
     IsDataProcessed = true;
    • Marked as answer by Bhavesh Shura Wednesday, February 22, 2012 5:15 PM
    Friday, July 29, 2011 6:53 PM

All replies

  • Not really. You can check what IL is emitted for your code (or go all the way and look with the debugger at the actual native code that gets executed), but I'm pretty sure you won't see anything like that. If the C# compiler ever tried something like that, pretty much every program out there would fail horribly.

    I presume you observed something different... care to elaborate?

    Thanks
    --mc

    • Marked as answer by eryang Tuesday, August 9, 2011 3:27 AM
    • Unmarked as answer by Bhavesh Shura Wednesday, February 22, 2012 5:15 PM
    • Unmarked as answer by Bhavesh Shura Wednesday, February 22, 2012 5:15 PM
    Thursday, July 28, 2011 5:06 PM
  • It may happens due to either compiler/JIT optimization or CPU reordering.

     

    to prevent it, try MemoryBarrier, which disable it and caching in registers.

    Thread.MemoryBarrier();
    getDataFromDatabase();
    Thread.MemoryBarrier();
     IsDataProcessed = true;
    • Marked as answer by Bhavesh Shura Wednesday, February 22, 2012 5:15 PM
    Friday, July 29, 2011 6:53 PM