2013-09-28 76 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