0

I would like to do a non busy waiting for a variable to become non-null:

while (true)
{
    if (myStaticVar != null)
    {
        break;
    }
}

myStaticVar.DoSomething(); 

The myStaticVar could be set any time by any thread.

I am stuck to .net 4, so i can not use async/await.

clamp
  • 31,604
  • 74
  • 198
  • 296

2 Answers2

0

The correct solution would be to let your threads communicate via a .NET synchronization primitive such as AutoResetEvent. Lots of examples can be found on SO, for example, here.

That said, manual thread synchronization is a hard problem and easy to get wrong. If your code is not time-critical and you prefer the simplicity of "busy waiting", don't forget to yield processor time while doing so. Either add some Thread.Sleep in your loop or use SpinWait.SpinUntil.

Community
  • 1
  • 1
Heinzi
  • 159,022
  • 53
  • 345
  • 499
0

You could convert your variable into a property and use the set accessor to call a delegate.

void Main()
{
    _someAction = () => Console.WriteLine("Hello world!");

    myStaticVar = 20;
}

private static Int32 _myStaticVar;
private static Action _someAction;

public static Int32 myStaticVar 
{
    get
    {
        return _myStaticVar;
    }
    set
    {
        _myStaticVar = value;

        if (_someAction != null)
            _someAction();
    }
}
James Cockayne
  • 108
  • 1
  • 4