2012-09-01 35 views
5

這是情況。可以使用收益率返回「現場」JSON嗎?

我所用的工作: - ASP.NET MVC 4的Web API - IIS 7.0託管應用 - C#

我的Web API,它得到Intranet上的和正在測試來自遠程計算機的性能數據通過URL調用調用API,並返回JSON。但是,它必須在返回JSON之前先完成執行。例如,如果我將性能監視返回10秒,則必須等待10秒才能顯示所有數據值。

我想要做的就是實時獲取它,以便它在每秒鐘讀取性能計數器並以JSON顯示時返回一個值,而不是等待所有要檢索的內容,然後一次列出。我正在嘗試使用YIELD關鍵字來完成此操作,但它仍然無法正常工作。在該方法完全結束之前,JSON不會顯示在瀏覽器中。

下面是倉庫方法和協調控制器動作的代碼:

從LogDBRepository.cs:

public IEnumerable<DataValueInfo> LogTimedPerfDataLive(string macName, string categoryName, string counterName, 
              string instanceName, string logName, long? seconds) 
    { 
     iModsDBRepository modsDB = new iModsDBRepository(); 
     List<MachineInfo> theMac = modsDB.GetMachineByName(macName); 

     if (theMac.Count == 0) 
      yield break; 

     else if (instanceName == null) 
     { 
      if (!PerformanceCounterCategory.Exists(categoryName, macName) || 
       !PerformanceCounterCategory.CounterExists(counterName, categoryName, macName)) 
      { 
       yield break; 
      } 
     } 
     else if (instanceName != null) 
     { 
      if (!PerformanceCounterCategory.Exists(categoryName, macName) || 
       !PerformanceCounterCategory.CounterExists(counterName, categoryName, macName) || 
       !PerformanceCounterCategory.InstanceExists(instanceName, categoryName, macName)) 
      { 
       yield break; 
      } 
     } 
     else if (logName == null) 
     { 
      yield break; 
     } 

     // Check if entered log name is a duplicate for the authenticated user 
     List<LogInfo> checkDuplicateLog = this.GetSingleLog(logName); 
     if (checkDuplicateLog.Count > 0) 
     { 
      yield break; 
     } 

     PerformanceCounterCategory category = new PerformanceCounterCategory(categoryName, theMac[0].MachineName); 
     if (category.CategoryName == null || category.MachineName == null) 
     { 
      yield break; 
     } 

     List<LogInfo> logIt = new List<LogInfo>(); 
     if (category.CategoryType != PerformanceCounterCategoryType.SingleInstance) 
     { 
      List<InstanceInfo> instances = modsDB.GetInstancesFromCatMacName(theMac[0].MachineName, category.CategoryName); 

      foreach (InstanceInfo inst in instances) 
      { 
       if (!category.InstanceExists(inst.InstanceName)) 
       { 
        continue; 
       } 
       else if (inst.InstanceName.Equals(instanceName, StringComparison.OrdinalIgnoreCase)) 
       { 
        PerformanceCounter perfCounter = new PerformanceCounter(categoryName, counterName, 
                     inst.InstanceName, theMac[0].MachineName); 

        //CounterSample data = perfCounter.NextSample(); 
        //double value = CounterSample.Calculate(data, perfCounter.NextSample()); 
        string data = ""; 
        List<UserInfo> currUser = this.GetUserByName(WindowsIdentity.GetCurrent().Name); 

        string timeStarted = DateTime.Now.ToString("MM/dd/yyyy - h:mm:ss tt"); 

        List<string> dataValues = new List<string>(); 
        for (int i = 0; i < seconds; i++) 
        { 
         data = "Value " + i + ": " + perfCounter.NextValue().ToString(); 
         DataValueInfo datItUp = new DataValueInfo 
         { 
          Value = data 
         }; 
         yield return datItUp; 
         dataValues.Add(data); 
         Thread.Sleep(1000); 
        } 
        string timeFinished = DateTime.Now.ToString("MM/dd/yyyy - h:mm:ss tt"); 

        Log log = new Log 
        { 
         LogName = logName, 
         CounterName = perfCounter.CounterName, 
         InstanceName = perfCounter.InstanceName, 
         CategoryName = perfCounter.CategoryName, 
         MachineName = perfCounter.MachineName, 
         TimeStarted = timeStarted, 
         TimeFinished = timeFinished, 
         PerformanceData = string.Join(",", dataValues), 
         UserID = currUser[0].UserID 
        }; 
        this.CreateLog(log); 
        break; 
       } 
      } 
     } 
     else 
     { 
      PerformanceCounter perfCounter = new PerformanceCounter(categoryName, counterName, 
                     "", theMac[0].MachineName); 


      string data = ""; 
      List<UserInfo> currUser = this.GetUserByName(WindowsIdentity.GetCurrent().Name); 

      string timeStarted = DateTime.Now.ToString("MM/dd/yyyy - h:mm:ss tt"); 

      List<string> dataValues = new List<string>(); 

      for (int i = 0; i < seconds; i++) 
      { 
       data = "Value " + i + ": " + perfCounter.NextValue().ToString(); 
       DataValueInfo datItUp = new DataValueInfo 
       { 
        Value = data 
       }; 
       yield return datItUp; 
       dataValues.Add(data); 
       Thread.Sleep(1000); 
      } 
      string timeFinished = DateTime.Now.ToString("MM/dd/yyyy - h:mm:ss tt"); 

      Log log = new Log 
      { 
       LogName = logName, 
       CounterName = perfCounter.CounterName, 
       InstanceName = perfCounter.InstanceName, 
       CategoryName = perfCounter.CategoryName, 
       MachineName = perfCounter.MachineName, 
       TimeStarted = timeStarted, 
       TimeFinished = timeFinished, 
       PerformanceData = string.Join(",", dataValues), 
       UserID = currUser[0].UserID 
      }; 
      this.CreateLog(log); 
     } 

    } 

從LogController.cs:

[AcceptVerbs("GET", "POST")] 
    public IEnumerable<DataValueInfo> Log_Perf_Data(string machine_name, string category_name, string counter_name, string instance_name, 
            string log_name, long? seconds, string live, string enforceQuery) 
    { 
     LogController.CheckUser(); 

     // POST api/log/post_data?machine_name=&category_name=&counter_name=&instance_name=&log_name=&seconds= 
     if (machine_name != null && category_name != null && counter_name != null && log_name != null && seconds.HasValue && enforceQuery == null) 
     { 
      List<DataValueInfo> dataVal = logDB.LogTimedPerfDataLive(machine_name, category_name, counter_name, instance_name, 
            log_name, seconds).ToList(); 
      logDB.SaveChanges(); 
      foreach (var val in dataVal) 
       yield return val; 
     } 

     yield break; 
    } 

謝謝你你的時間和考慮。

+1

使用'yield'關鍵字創建的迭代器函數旨在根據請求提取下一個項目。它們不像彗星,它將數據從服務器推送到客戶端。也許你應該對彗星技術做一點研究。 –

+0

我不認爲解決方案很簡單,因爲客戶端代碼也會等待完整響應。 我同意@KendallFrey,如果你想這樣做,你將不得不使用彗星。 –

+0

謝謝。我會把彗星編碼放在控制器中嗎? – praetor

回答

1

yield僅在創建inmemory對象時纔會在刷新響應時返回。

可能最簡單的方法是將json放在同步(靜態?)變量的服務器上,當你提出顯示你創建json的性能數據的請求時,啓動後臺工作器(google for web backgrounder nuget)將數據填充到json對象中,設置運行標誌並返回json對象(可能在開始時爲空)。

然後,使用瀏覽器中的setInterval,您每秒鐘都會通過調用服務器來刷新此數據,因此每次獲得具有越來越多數據的響應時都是如此。當後臺線程完成時,您將運行標誌設置爲false,並在下一次調用中返回您的json的信息,以便您可以停止從客戶端刷新。

這是不是最好的方法,但可能最容易實現。