开发者

Threadstart in a loop in a timer only executing last thread in said loop.

开发者 https://www.devze.com 2023-04-04 02:35 出处:网络
I have a timer executing a loop executing a series of threads. Each thread simply polls a serial device (on unique ports) and writes the data to a MySQL Database for pickup by a web application.

I have a timer executing a loop executing a series of threads. Each thread simply polls a serial device (on unique ports) and writes the data to a MySQL Database for pickup by a web application.

I am noticing only the last thread in the loop is being executed.

Here is my timer Interval method.

static void glob_timer_Elapsed(object sender, ElapsedEventArgs e)
{
    foreach (object[] row in user_ids)
    {
        Console.WriteLine(row[0].ToString() + ":" + row[1].ToString());
        ThreadStart starter = delegate { Functions.UpdateFor(row[0].ToString(), row[1].ToString()); };
        new Thread(starter).Start();
    }
}

user_ids is a List<object[]> containing rows from a query; so row[0] = user ID, row[1] = Com Port Name

In the function UpdateFor():

public static void UpdateFor(string uid, string com_name)
{
    try
    {
        Console.WriteLine("[" + uid + "]- " + DateTime.Now.ToString() + " : " + "Begin read transmission.");

When this is run, in the console I see

 1:COM1 
 2:COM2
 [2]-{DateTime} : Begin read transmission

Why am I not seeing the UpdateFor for uid 1.

Note: I have also verif开发者_如何学JAVAied the data that is supposed to be written to the DB from COM1 is never written.


You are suffering from a closure problem. Each delegate captures the reference to object[] row in each loop, iteration, thus they all execute with the same reference, namely whatever the value of row ended up being. You need to simply assign an inner variable to make sure each delegate gets a unique reference.

 foreach (object[] row in user_ids)
 {
    var innerReference = row;
    Console.WriteLine(innerReference[0].ToString() + ":" + innerReference[1].ToString());
    ThreadStart starter = delegate { Functions.UpdateFor(innerReference[0].ToString(), innerReference[1].ToString()); };
    new Thread(starter).Start();
 }
0

精彩评论

暂无评论...
验证码 换一张
取 消