线程C#停止执行程序,而不使用线程使程序保持运行

时间:2011-11-03 19:41:04

标签: c# multithreading

我在C#中使用-first time-threads -with multiparameters-我遇到的问题是:

如果我使用这些功能 - 我会发布它 - 没有威胁,它将遵循程序的自然逻辑。不过,我需要同时使用线程来调用函数的多个实例。但是当我使用线程时,程序的执行停止,虽然我知道该线程正在调用该函数,因为我看到它 - 在Windows中弹出形成!它会打印一些我写的消息 -

我不知道为什么,功能比较简单。我认为它可能是 EventArgs 的东西,但不确定 - 我也将它作为参数传递! - 。

让我们看看线程和功能:

 //This is the function that I call in the threads
 public void device(object i, object s, object f)
 {
     int j = (int)i;
     EventArgs g = (EventArgs)f;

      //Connect the devices
      BSSDK.BS_SetDeviceID(m_ConnectedDeviceHandle[j],
          m_ConnectedDeviceID[j], m_ConnectedDeviceType[j]);

      UserManagement userTest = new UserManagement();

      userTest.SetDevice(m_ConnectedDeviceHandle[j],
          m_ConnectedDeviceID[j], m_ConnectedDeviceType[j]);

      //Open a windows form and show the interface!
      userTest.Show();
    }


   // The function with the threads
   private void userTest_Click(object sender, EventArgs e)
   {
        ...

        //This loop if for testing, the actual value will be other.
        for (int i = 0; i < 2; i++)
        {

            //Notice that I´m sending 3 parameters!
            Thread t = new Thread(unused => device(i, sender, e));

            try
            {
                t.Start();
            }
            catch (ThreadStateException f)
            {
                MessageBox.Show("ERROR:" + f);  
            }
         }
       }

谢谢。

2 个答案:

答案 0 :(得分:3)

线程结束时,您的表单超出了范围。你需要做一些事情来保持对它的引用。

与来自不同线程的控件进行交互通常也是一个坏主意。尝试从创建控件的线程以外的线程访问控件可能会导致交叉线程异常。您必须调用Invoke或BeginInvoke来编组对正确线程的调用。

答案 1 :(得分:0)

如果这是你第一次看到线程,我建议你停在这里看看别的东西!:) 首先,您在这里尝试做的是新的Async库(http://msdn.microsoft.com/en-us/vstudio/gg316360)的完美候选者。请注意,尽管它是CTP,但MS确实支持使用此配置。

如果您确实需要使用与提供的线程类似的内容,则可以使用任务并行库。您可以将任务视为轻量级线程。

我今天使用线程的唯一情况是当我有一个长时间运行的操作时,我需要完全控制。

致以最诚挚的问候,

提笔

相关问题