C
C#•3y ago
Metalkon

HttpClient only working in Main but not in another Class? [Answered]

I'm currently following a c# json tutorial and trying to put this code into it's own class so I can keep multiple code references in a single project. Everything works fine in Main but when I try to put it into another class it won't work properly, anyone have an idea on what I might be missing? When I run it in main I get the json details printed in the console window, but when i run it in the class it's blank. The only thing in the main method is JsonServer.Run();
18 Replies
TheRanger
TheRanger•3y ago
that's because your program ended execution before the Run Method did because its running asynchronously, you need to await the method
Metalkon
MetalkonOP•3y ago
ahh that makes sense, not sure how to await a method though. 🙂 (first time using await lol)
TheRanger
TheRanger•3y ago
await JsonServer.Run(); ofc the Main Method also needs to be an async Task
Metalkon
MetalkonOP•3y ago
is there any way around that so i can keep the main method mostly untouched?
TheRanger
TheRanger•3y ago
JsonServer.Run().Result; but i wouldn't recommend it may cause deadlocks
Metalkon
MetalkonOP•3y ago
hmm
TheRanger
TheRanger•3y ago
why do you want ur main method to be untouched?
Metalkon
MetalkonOP•3y ago
Gonna have like 10 different unrelated little things in the project that i can access from a menu do tests and check everything in a single project. reading input, reading jsons, various db things and actions all for testing/learning and as a reference for later projects so i dont have a dozen separate projects
TheRanger
TheRanger•3y ago
i don't think an async Task Main method would affect any of them
Unknown User
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
Metalkon
MetalkonOP•3y ago
namespace CS_Code_References
{
public class Program
{
public static async Task Main()
{
JsonServer.Run();
}
}
}
namespace CS_Code_References
{
public class Program
{
public static async Task Main()
{
JsonServer.Run();
}
}
}
something like this?
TheRanger
TheRanger•3y ago
u forgot to await .
Metalkon
MetalkonOP•3y ago
Metalkon
MetalkonOP•3y ago
working now
TheRanger
TheRanger•3y ago
looks perfect
Metalkon
MetalkonOP•3y ago
🙂 ty for the help,
TheRanger
TheRanger•3y ago
u can write /close to close this thread
Accord
Accord•3y ago
✅ This post has been marked as answered!
Want results from more Discord servers?
Add your server