C#多线程代码没有达到断点

时间:2014-05-16 21:41:20

标签: c# multithreading

请查看下面的示例代码,当我在“testmethod”中放置一个断点并运行应用程序时,它没有到达断点。这段代码好吗?

    static void Main(string[] args)
    {
        Thread[] testthreads = new Thread[3];
        List<int> testdata = new List<int>();
        testdata.Add(1);
        testdata.Add(2);
        testdata.Add(3);

        int i = 0;
        foreach (int data in testdata)
        {
            testthreads[i] = new Thread(new ThreadStart(() => testmethod(data)));
            testthreads[i].Name = string.Format("Working Thread: {0}", data);
            i++;
        }
    }

    static void testmethod(int i)
    {
        try
        {
            //DataTable dt = DB.GetData(i);
            if (dt.Count > 0)
            {
                Console.WriteLine("Count: {0}", dt.Count);
            }
        }
        catch (Exception ex) 
        { 
            throw ex; 
        }
    }

我尝试了另一种方法,它总是返回第一个输入的名称。

方法2:

static void Main(string [] args) {     列出testdata = new List();     testdata.Add(111111);     testdata.Add(222222);     testdata.Add(333333);

foreach (int data in testdata)
{
    new Thread(delegate()
    {
        DataTable dt = DB.GetData(data);
        if (dt.Count > 0)
        {
            Console.WriteLine("Name: {0}", dt.Rows[0]["Name"];);
        }

        // Signal the CountdownEvent.
        countdownEvent.Signal();
    }).Start();
}

// Wait for workers.
countdownEvent.Wait();
Console.WriteLine("Finished."); 

}

输出:

Name: JULIE
Name: JULIE
Name: JULIE

始终返回111111的值(名称)

1 个答案:

答案 0 :(得分:12)

你需要启动线程。

testthreads[i] = new Thread(new ThreadStart(() => testmethod(data)));
testthreads[i].Name = string.Format("Working Thread: {0}", data);
testthreads[i].Start();