任何人都知道為什么Task.Run下面沒有做任何事情就結束了,而如果只保留那一行:
var someDump = Helper.MakeRequest(body, Helper.GetUrl(2, ConfigurationManager.AppSettings["SomeId"]), 2);
它會無縫地作業嗎??
謝謝!
PS:它只會列印出“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();
uj5u.com熱心網友回復:
您需要在最后等待任務:
await t2;
您的函式在任務有機會完成之前退出
uj5u.com熱心網友回復:
您的代碼創建了兩項任務,而不僅僅是一項。這段代碼:
var t2 = Task.Run(() =>
{
//...
}).ContinueWith(t => Console.WriteLine("t2 done."));
...相當于:
Task t1 = Task.Run(() =>
{
//...
});
Task t2 = t1.ContinueWith(t =>
{
Console.WriteLine("t2 done.");
});
不同之處在于,在第一種情況下,您無權訪問該t1任務,因此您無法訪問該任務await并觀察可能發生的任何錯誤。t2通過檢查引數的IsFaulted/Exception屬性,您觀察可能錯誤的最后機會是在主體內部t。你沒有,所以現在你永遠不會知道t1任務內部發生了什么。
附帶說明一下,這ContinueWith是一種原始方法,充滿陷阱和細微差別,不建議在應用程式代碼中使用它。如果您正在撰寫一個庫并且您完全了解它的細微差別和陷阱,那么此建議不適用。但是對于一般用途,async/await技術提供了撰寫正確且可維護的異步代碼所需的一切。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/318799.html
