2016-05-16 53 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執行完成,用戶可以訪問其他功能,因此最終它將成爲同步方法。你能否提出你的建議? –