Anyone knows why the Task.Run
below just ends without doing anything, while if only keep that line:
var someDump = Helper.MakeRequest(body, Helper.GetUrl(2, ConfigurationManager.AppSettings["SomeId"]), 2);
it will work seamlessly??
Thank you!
PS: It will just print out "t2 done".
var t2 = Task.Run(() =>
{
string filePath = System.Web.HttpContext.Current.Server.MapPath("~/" ConfigurationManager.AppSettings["ServerPoolsFile"]);
var someDump = Helper.MakeRequest(body, Helper.GetUrl(2, ConfigurationManager.AppSettings["SomeId"]), 2);
JObject wfOutput = JObject.Parse(someDump.WFOutput);
var jsonData = wfOutput["output-parameters"];
var poolsList = jsonData[0]["value"]["string"]["value"];
JObject siteJson = JObject.Parse(poolsList.ToString());
filePath = filePath "_" siteJson["site"].ToString() ".json";
if (!System.IO.File.Exists(filePath))
{
// Create a file to write to.
using (StreamWriter sw = System.IO.File.CreateText(filePath))
{
sw.WriteLine(poolsList.ToString());
}
}
else
{
System.IO.File.WriteAllText(filePath, poolsList.ToString());
}
}).ContinueWith(t => Console.WriteLine("t2 done."));
Task.Yield();
CodePudding user response:
You need to await the task at the end:
await t2;
Your function exits before the task had a chance to finish
CodePudding user response:
Your code creates two tasks, not just one. This code:
var t2 = Task.Run(() =>
{
//...
}).ContinueWith(t => Console.WriteLine("t2 done."));
...is equivalent to this:
Task t1 = Task.Run(() =>
{
//...
});
Task t2 = t1.ContinueWith(t =>
{
Console.WriteLine("t2 done.");
});
The difference is that in the first case you don't have access to the t1
task, and so you can't await
it and observe any error that may have occured. Your last chance to observe a possible error was inside the t2
body, by examining the IsFaulted
/Exception
property of the t
argument. You didn't, so now you'll never know what happened inside the t1
task.
As a side note the ContinueWith
is a primitive method, full of gotchas and nuances, and using it in application code is not advisable. If you are writing a library and you are fully aware of its nuances and pitfalls, then this advice doesn't apply. But for general usage, the async/await technology offers everything that you need for writing correct and maintainable asynchronous code.