2013-09-28 70 views
0

我有一個列表。我把我所有的查詢輸出。現在使用 線程做一些處理。所以當工作完成後,需要更新列表項值。 請參閱我下面的代碼:如何更新列表的項目值?

公開宣稱列表:

public static List<string[]> OutboxList = new List<string[]>(); 

從數據庫中讀取數據和操作的列表:

OutboxQueryCommand.CommandText = "SELECT top 5 id, status from TableA";  
SqlDataReader OutboxQueryReader = OutboxQueryCommand.ExecuteReader(); 

while (OutboxQueryReader.Read()) 
{ 
    string[] OutBoxFields = new string[7]; 
    OutBoxFields[0] = OutboxQueryReader["id"].ToString(); 
    OutBoxFields[1] = OutboxQueryReader["status"].ToString(); 
    OutboxList.Add(OutBoxFields); 
} 

foreach (string[] OutBoxFields in OutboxList) 
{ 
    id = OutBoxFields[0]; 
    status = OutBoxFields[1]; 

    Thread OutboxThread = new Thread(() => OutboxThreadProcessor(id,status)); 
    OutboxThread.Start(); 
} 

打電話線程的方法:

static void OutboxThreadProcessor(string id,string status) 
    { 
//predefine value of status is "QUE". Process some work here for that perticular item list.if data process success full then need to update 
// the status of the list item 

// need to update the perticular value of that list item here. 
How i do it??????? 
//Say for Example 1-> Success 
//   2-> Failed 
//   3-> Success    
    } 

回答

1

數組直接傳遞到Thread這樣就可以更新陣列,一旦你」:如果你更換七個string項的數組與class是有七個字符串字段,這樣你的程序將更加可讀重做。

static void OutboxThreadProcessor(string[] OutBoxFields) 
{ 
    string id = OutBoxFields[0]; 
    string status = OutBoxFields[1]; 

    //Do work 

    OutBoxFields[0] = "2";//update the array 
    OutBoxFields[1] = "something"; 
} 

這樣稱呼它

Thread OutboxThread = new Thread(() => OutboxThreadProcessor(OutBoxFields)); 
OutboxThread.Start(); 

另外請注意,您要關閉了此方案中的循環,這是好的,如果你正在構建在C#5.0的編譯器,這是好的,否則你需要在循環中使用局部變量。

+0

靜態列表通過線程顯示error..can你請幫忙嗎?線程OutboxThread =新線程((()=> OutboxThreadProcessor(OutboxList)); – riad

+0

您正在傳遞列表變量'OutboxList'。看看我的答案,你應該通過'OutBoxFields' –

+0

我已經嘗試了OutboxFileds。但都顯示錯誤..線程OutboxThread =新的線程((()=> OutboxThreadProcessor(OutBoxFields));有沒有限制列表.. ?? – riad

1

您需要在陣列列表中找到一個項目item[0]等於id,並將status設置爲item[1]。你可以用一個循環做到這一點,像這樣

foreach (string[] item in OutboxList) { 
    if (item[0] == id) { 
     item[1] = status; 
     break; 
    } 
} 

或LINQ,像這樣:

var item = OutboxList.FirstOrDefault(a => a[0] == id); 
if (item != null) { 
    item[1] = status; 
} 

請注意,您的數據結構並不特別面向對象的。

class OutBoxFields { 
    public string Id {get;set;} 
    public string Status {get;set;} 
    ... // and so on 
} 
+0

感謝您的建議。但是,這個代碼塊的非工作到OutboxThreadProcessor方法..是否有任何更新需要? – riad

+0

「OutboxThreadProcessor」是一個靜態方法,它與您的靜態「OutboxList」字段定義在同一個類中? – dasblinkenlight