Hello, I want to consume REST api. I use code like this:
namespace test2
{
class Program
{
static void Main(string[] args)
{
TestRest t = new TestRest();
t.Run();
}
}
public class TestRest
{
public TestRest() { }
public async void Run()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://community-league-of-legends.p.mashape.com/");
client.DefaultRequestHeaders.Add("X-Mashape-Authorization", "tcsgoutBcXP5Lu5L2jYBOu4qeXehseiH");
HttpResponseMessage response = await client.GetAsync("api/v1.0/euw/summoner/getSummonerByName/NICK_FROM_GAME");
JObject response2 = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()) as JObject;
foreach (KeyValuePair<string, JToken> j in response2)
{
Console.WriteLine("Key:{0} Value:{1}", j.Key, j.Value);
}
}
}
}
But while calling method:
await client.getAsync("...
program is exiting. Please help me, its simple console app to consume simple api and i can not manage this :(
Thanks
There are two problems here:
void
async method, which is almost always a bad idea unless it's meant to be an event handler. You should generally make an async method return Task
where you'd normally write a void
synchronous method.The simplest fix is to address both at the same time - just make the async method return Task
, and then use:
static void Main(string[] args)
{
TestRest t = new TestRest();
t.Run().Wait();
}
Note that that would be a really bad idea in a WinForms app, as waiting on a Task
in the UI thread would basically cause a deadlock. However, in a console app there's no equivalent of the UI thread, so task continuations are scheduled on the thread pool - your "main" thread will block, the continuation in your async method will run on a thread pool thread, and then when that's completed the task that the main thread is waiting for will complete.
See more on this question at Stackoverflow