C
C#•2y 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•2y ago
that's because your program ended execution before the Run Method did because its running asynchronously, you need to await the method
Metalkon
Metalkon•2y ago
ahh that makes sense, not sure how to await a method though. 🙂 (first time using await lol)
TheRanger
TheRanger•2y ago
await JsonServer.Run(); ofc the Main Method also needs to be an async Task
Metalkon
Metalkon•2y ago
is there any way around that so i can keep the main method mostly untouched?
TheRanger
TheRanger•2y ago
JsonServer.Run().Result; but i wouldn't recommend it may cause deadlocks
Metalkon
Metalkon•2y ago
hmm
TheRanger
TheRanger•2y ago
why do you want ur main method to be untouched?
Metalkon
Metalkon•2y 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•2y ago
i don't think an async Task Main method would affect any of them
Unknown User
Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
Metalkon
Metalkon•2y 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•2y ago
u forgot to await .
Metalkon
Metalkon•2y ago
Metalkon
Metalkon•2y ago
working now
TheRanger
TheRanger•2y ago
looks perfect
Metalkon
Metalkon•2y ago
🙂 ty for the help,
TheRanger
TheRanger•2y ago
u can write /close to close this thread
Accord
Accord•2y ago
✅ This post has been marked as answered!