2016-12-15 67 views
0

的巨量我必須處理龐大的數據量批處理作業C#異步的foreach循環的數據

程序流程

var inputDataLst = contextObj.GetData(); //More that 10000 rows I will retrieve 

foreach(var item in inpDataLst) 
{ 
    //logic 
} 

Call context.SaveMethod(inpuDataLst); 

我試圖做類似

var tsklst = inputDataLst.Select(async pItem => 
{ 
    //Logic 
}); 

await Task.WhenAll(taskList); 

編譯器發出警告,Resharper建議我做一個同步方法。

任何人都可以建議我如何處理這一點,因爲我將有巨大的數據我也喜歡做異步操作..

循環完成我得到落實後,建議@bruno

Parallel.ForEach(taskList, item => { 
item.StatusId = 2; //Completed 
LastUpdateUser = "Batch"; 
}); 

taskList是NULL,

+3

這是真的異步,你是後,還是平行?你在做什麼邏輯?如果它不使用共享狀態,您可以使用Linq的IEnumerable .AsParallel()方法,或者您可以使用Parallel.For – Clint

+0

我不想逐個處理該記錄。 – RajGan

+1

可以顯示警告編譯器正在顯示? – oqx

回答

5

您應該使用Parallel.For。它會異步處理你的列表。

var inputDataLst = contextObj.GetData(); 


Parallel.For(0, inputDataLst.Length, 
       index=> 
       { 
        //your logic, something like ProcessData(inputDataLst[index]) 
       }); 

context.SaveMethod(inpuDataLst); 

你也使用Parallel.ForEach

Parallel.ForEach(inpuDataLst, item => { ProcessData(item) }); 

編輯:

根據你修改的其他評論,我寫了一個很簡單的最小工作示例:

using System; 
using System.Collections.Generic; 
using System.Diagnostics; 
using System.Threading.Tasks; 

namespace SO.RajGan 
{ 
    class SomeData 
    { 
     public int StatusId { get; set; } 
     public string LastUpdateUser { get; set; } 

     public override string ToString() 
     { 
      return $"Last update user: {LastUpdateUser}; Status ID = {StatusId}"; 
     } 
    } 

    class Program 
    { 
     static void Main(string[] args) 
     { 
      var dataList = new List<SomeData>(); 

      for(int i = 0; i < 100000; i++) 
      { 
       dataList.Add(new SomeData() { StatusId = new Random(i).Next(1, 10), LastUpdateUser = $"User {i + 1}" }); 
      } 

      Parallel.ForEach(dataList, item => 
      { 
       item.LastUpdateUser = "Batch"; 
       item.StatusId = 2; 
      }); 

      Debug.Assert(dataList != null); 
     } 
    } 
} 

我測試它,它工作,dataList不是空的,所有條目都相應更新。如果沒有看到代碼,我無法追蹤列表爲空的原因。

+0

謝謝布魯諾,我試圖實現你的解決方案,它的返回null。我將在processdata()方法中做的所有事情都是改變item的屬性值。所以我希望更改應該反映在inputDataList中。但我得到空。我更新了上面的代碼。 – RajGan

+0

是的,它爲我工作。對不起,我犯了一個非常愚蠢的錯誤。 contextObj.GetData();正在迴歸無數,我發現它無法平行保留這些優勢。但是當我返回LIst <>然後它工作正常.. – RajGan