C#C
C#•2y ago
UnemployedNinja

Thread.sleep in a constructor

Since you can't await in a constructor, I'm calling an async method and just sleeping the thread for 10ms while the task is incomplete:
private readonly string _Value;
public MyClass() { // Constructor
  Task<string> task = GetMyValue(); // Makes an asynchronous Http request
  while (!task.IsCompleted) Thread.Sleep(10);
  _Value = task.Result;
}
Is this ok, or is there a better way to do this?

... or should I just be designing my code better in the first place? 😬
Was this page helpful?