C
C#•9mo 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;
}
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? 😬
8 Replies
mtreit
mtreit•9mo ago
No that's terrible. Don't do anything expensive in your constructor. You probably want to use a Lazy<T>
Jimmacle
Jimmacle•9mo ago
if you need to await data your class requires to be constructed you could use a static factory method that can be made async
UnemployedNinja
UnemployedNinjaOP•9mo ago
That's what I thought :/ hmm I might go this route, ty
Angius
Angius•9mo ago
public class Foo
{
private Foo(X x){}
public static async Task<Foo> Instantiate()
{
var x = await GetX();
return new Foo(x);
}
}
public class Foo
{
private Foo(X x){}
public static async Task<Foo> Instantiate()
{
var x = await GetX();
return new Foo(x);
}
}
ez
UnemployedNinja
UnemployedNinjaOP•9mo ago
Yea, I did it like this lol
jcotton42
jcotton42•9mo ago
What kind of class is this anyhow?
UnemployedNinja
UnemployedNinjaOP•9mo ago
It's used to create a websocket client. The server I'm connecting to has a service API, which is used to get the websocket server for different regions. And the websocket client requires a URL to be created I could just contact the service API before, and then create the client, but I'd like to do it all in one It's for a library I'm creating, so I'd like to minimize the steps required
Unknown User
Unknown User•9mo ago
Message Not Public
Sign In & Join Server To View
Want results from more Discord servers?
Add your server