在检查线程IsAlive时条件失败或在C#中为null

时间:2016-09-08 08:02:28

标签: c# multithreading

我正在开发一个小的excel应用程序,因为我使用3个线程读取一些函数。根据复选框选择,不必调用所有线程来读取特定函数,特定线程将运行。

我在全球部分定义的线程如下所示。

 Thread Run_thread = null, Run_thread1 = null, Run_thread2 = null;

/ *根据复选框选择* /

调用线程
     if ((checkBox1.Checked == true) && (textBox2.Text != ""))
                {
                    Run_thread = new Thread(() => READ_MAPPING_FILE_PATHS(textBox2.Text, 5, 15));
                    Run_thread.Start();
                    check++;
                }
                if ((checkBox2.Checked == true) && (textBox5.Text != ""))
                {
                    Run_thread1 = new Thread(() => READ_MAPPING_FILE_PATHS(textBox5.Text, 7, 9));
                    Run_thread1.Start();
                    check++;
                }
                if ((checkBox3.Checked == true) && (textBox6.Text != ""))
                {
                    Run_thread2 = new Thread(() => READ_MAPPING_FILE_PATHS(textBox6.Text, 5, 15));
                    Run_thread2.Start();
                    check++;
                }

现在如果用户选择复选框1和checkbox2,则Run_thread1和Run_thread将处于IsAlive状态,Run_thread2将为null;

现在检查线程是否存在

    if (!(Run_thread.IsAlive || Run_thread1.IsAlive || Run_thread2.IsAlive))
                    {
                      //do something
                    }

                   else
                    {
                             //message thread are in running mode.
                     }
检查Run_thread2状态时,

上面的检查错误

 "Object reference not set to an instance of an object."

可以帮助我解决这个问题。我是新手。

1 个答案:

答案 0 :(得分:1)

显然,如果您不创建实例,则某些字段将为null,您可以根据相应的复选框进行实例。

试试这个:

if (!(Run_thread != null && Run_Thread.IsAlive) ||
     (Run_thread1 != null && Run_thread1.IsAlive) ||
     (Run_thread2 != null && Run_thread2.IsAlive))