Is this bad practice with static classes and thread safety?

Assuming I'm not using a lock statement, is this bad practice?

public static class Foo
{
  public static string Bar()
  {
    bool working;

    while (working)
    {
      // Loop until ready to run.
    }

    working = true;

    // Do stuff here.

    working = false;
    return "done."
  }
}

Edit -

Having tried something like this, I understand that this is not possible for several reasons. I was just curious. The example I wrote does not even work.

+3
source share
6 answers

Loop is the process of consuming a processor.

I mean, everything you do is just waiting. This is not good.

+4
source

-, , . 2 , , "". , .

. 2 , () , working = true; .

.

+4

, , working , :

  • volatile static. Volatile , "" .

  • " ". , . , , ​​ working.

+2

, .

? Monitor, .

- .

+1

: ( , ), , , . , ​​ " ", , System.Threading.Thread.MemoryBarrier.

But you should use locks instead. Free programming is incredibly difficult to get right.

+1
source

Using locks is the only way to prevent concurrency problems (others that don't).

public static class Foo
{
  private static object barLock = new object();

  public static string Bar()
  {
    lock (barLock)
    {
      // Do work
      return "Done";
    }
  }
}
0
source

Source: https://habr.com/ru/post/1704741/


All Articles