2016-05-16 25 views
0

我正在使用MVC C#Razor Framework 4.6。使用任务运行(异步)响应中的部分视图更新UI

我有静态方法ExportManager.ExportExcelCannedReportPPR包装在Task.Run长期运行的报告。此方法返回boolean值并基于此我刷新部分视图(_NotificationPanel)。

public ActionResult ExportCannedReport(string cannedReportKey, string cannedReportName) 
{    
    string memberKeys = _curUser.SecurityInfo.AccessibleFacilities_MemberKeys; //ToDo: Make sure this is fine or need to pass just self member? 
    string memberIds = _curUser.SecurityInfo.AccessibleFacilities_MemberIDs; //ToDo: Make sure this is fine or need to pass just self member? 
    string curMemberNameFormatted = _curUser.FacilityInfo.FacilityName.Replace(" ", string.Empty); 
    string cannedReportNameFormatted = cannedReportName.Replace(" ", string.Empty); 
    string fileName = string.Concat(cannedReportNameFormatted, "_", DateTime.Now.ToString("yyyyMMdd"), "_", curMemberNameFormatted); 
    //ToDo: Make sure below getting userId is correct 
    string userId = ((_curUser.IsECRIStaff.HasValue && _curUser.IsECRIStaff.Value) ? _curUser.MembersiteUsername : _curUser.PGUserName); 

    var returnTask = Task.Run<bool>(() => ExportManager.ExportExcelCannedReportPPR(cannedReportKey, cannedReportName, fileName, memberIds, userId)); 
    returnTask.ContinueWith((antecedent) => 
    { 
     if (antecedent.Result == true) 
     { 
      return PartialView("_NotificationPanel", "New file(s) added in 'Download Manager'."); 
     } 
     else 
     { 
      return PartialView("_NotificationPanel", "An error occurred while generating the report."); 
     } 
    }, TaskContinuationOptions.OnlyOnRanToCompletion); 

    return PartialView("_NotificationPanel", ""); 
} 

现在的问题是,即使在_NotificationPanel得到ContinueWith执行UI没能刷新。

+0

你真的希望在该代码中发生什么? –

回答

1

问题是,一旦你从它返回 - 该请求完成。对于单个请求,您无法多次返回。请求和响应是1比1。您需要在此处使用asyncawait,以便在导出完成后才返回结果。

public async Task<ActionResult> ExportCannedReport(string cannedReportKey, 
                string cannedReportName) 
{    
    // Omitted for brevity... 

    var result = 
     await Task.Run<bool>(() => 
      ExportManager.ExportExcelCannedReportPPR(cannedReportKey, 
                cannedReportName, 
                fileName, 
                memberIds, 
                userId)); 

    return PartialView("_NotificationPanel", 
     result 
      ? "New file(s) added in 'Download Manager'." 
      : "An error occurred while generating the report."); 
} 

你需要使该方法返回Task这样,这是“awaitable”。然后您将该方法标记为async,该关键字启用await关键字。最后,您准备好执行长时间运行的任务,并从结果中正确地确定并返回所需的局部视图更新。

更新

或者,可以一旦服务器响应利用客户端和更新上的AJAX调用。有关具体结帐的详细信息,请参阅MSDN

+0

谢谢大卫。实际上,这使用户可以访问其他功能。一旦Task.Run执行完成,用户可以访问其他功能,因此最终它将成为同步方法。你能否提出你的建议? –