在的ThreadStart仅在执行最后一个线程的计时器循环说循环。 [英] Threadstart in a loop in a timer only executing last thread in said loop.

查看:180
本文介绍了在的ThreadStart仅在执行最后一个线程的计时器循环说循环。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有执行执行一系列线程的回路的计时器。每个线程只需轮询串行设备(独特的端口),并将数据写入到MySQL数据库通过一个Web应用程序皮卡。

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是列表< [对象]> 包含从查询的行;所以行[0] = 用户ID 行[1] = COM端口名称

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

在功能 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

为什么我没有看到 UpdateFor 的UID 1。

Why am I not seeing the UpdateFor for uid 1.

请注意:我也已经验证,应该是从COM1写入DB永远不会写入数据。

Note: I have also verified 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();
 }

这篇关于在的ThreadStart仅在执行最后一个线程的计时器循环说循环。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆