它的工作原理!
这里是我做了什么:
步骤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表示完整)。
所以是的,希望能帮助其他人尝试做类似的事情。
优秀的问题...坚持在相同的情况! –