I have the sample code below in an ASP.NET MVC application. I am not able to get the data at all. In otherwords even though I am awaiting for the completion of the task Nothing happens and control never returns to the Index Action. What am I missing?
public class HomeController : Controller
{
//
// GET: /Home/
public async Task<ActionResult> Index()
{
Task<string> getContentsTask = GetContentsAsync();
string contents = await getContentsTask;
return Content("ssss");
}
async Task<string> GetContentsAsync()
{
int sample = 0;
HttpClient client = new HttpClient();
Task<string> contents = client.GetStringAsync("http://www.msdn.com");
string data = await contents;
return data;
}
}
Tried this in a console application and even in this the application exited as soon as i called the first await.
class Program
{
static void Main(string[] args)
{
GetContents();
}
public static async void GetContents()
{
Task<string> newTask = GetContentsAsync();
string contents = await newTask;
Console.WriteLine(contents);
Console.ReadLine();
}
public static async Task<string> GetContentsAsync()
{
HttpClient client = new HttpClient();
Task<string> getStringTask = client.GetStringAsync("http://www.msdn.com");
string content = await getStringTask;
return content;
}
}
When I give a Thread.Sleep(8000); then this is working fine. The calls are returning correctly.
Task<string> getContentsTask = GetContentsAsync();
Thread.Sleep(10000);
string contents = await getContentsTask;