它的工作原理!
這裏是我做了什麼:
步驟1 & 2 - 動作方法被調用,長期運行的線程啓動
當我的操作方法被調用,它會生成一個唯一的ID。然後我實例化一個我的PdfGenerator
類的實例,創建一個新線程,調用PdfGenerator.Generate
並啓動它。
public class PdfGenerator
{
public string State;
public byte[] Data;
public void Generate()
{
// Generate PDF/Long running process
// Should update State as it goes
// ...
// Once finished, Data is populated with the binary byte[]
}
}
一旦線程已經啓動(或啓動前)發電機實例存儲在緩存:
HttpContext.Cache[guid] = generator;
我還附上了GUID來的ViewData的,這樣它可以在我看來參考腳本。
步驟3 & 4 - 顯示和更新狀態/發展觀
現在,線程運行和生成PDF已經開始,我可以顯示我的進步視圖腳本。使用jQuery的$.getJSON
我能夠查詢一個單獨的行動,找到代的狀態:
[OutputCache(Duration = 0, VaryByName = "none", NoStore = true)]
public JsonResult CheckPdfGenerationStatus(string guid)
{
// Get the generator from cache
var generator = HttpContext.Cache[guid] as PdfGenerator;
if (generator == null)
return Json(null);
else
return Json(generator.State);
}
我的看法腳本解釋JSON和顯示相應的進度信息。
步驟5 - 當前文件到用戶
一旦生成完成,發生器狀態被相應地設置,並且當jQuery的接收該信息,它可以使可用的鏈接,或者直接使用發送文件javascripts location.href
。
指建立和返回文件只是獲取發電機從緩存中,並返回所附的byte []
public ContentResult DownloadPdf(string guid)
{
var generator = HttpContext.Cache[guid] as PdfGenerator;
if (generator == null)
return Content("Error");
if (generator.State == "Completed")
{
return Content(generator.Data);
}
else
{
return Content("Not finished yet");
}
}
我的我的實際工作中我有更詳細的狀態,如初始化操作方法,正在運行並完成。以及進度百分比(以小數表示,1.0表示完整)。
所以是的,希望能幫助其他人嘗試做類似的事情。
優秀的問題...堅持在相同的情況! –