4

由于一些 GUI 滞后(表单变得无响应)问题,我已经在新线程中启动了一个表单。该线程在调用函数 (some_function()) 时启动。如...

/*========some_function=========*/
     void some_function()
     {
          System::Threading::Thread^ t1;
          System::Threading::ThreadStart^ ts = gcnew System::Threading::ThreadStart(&ThreadProc);
          t1 = gcnew System::Threading::Thread(ts);
          t1->Start();
          while(condition)
          {
               Form1^ f1=gcnew Form1();
              //some coding
              //to change the values of a different form (Form1)
          }
     }

/*======ThreadProc=========*/
    void ThreadProc()
    {
         Form1^ f1=gcnew Form1();
         f1->Show(); //OR Application::Run(Form1());
    }

现在的问题是关于在“while”循环中更改表单(Form1)的值,例如标签文本、进度条等。是否有任何方法可以更改在不同线程中打开的表单值?

4

1 回答 1

0

检查Control::Invoke以将方法扔到安全线程中以更改控件。要显示示例的形式:

public delegate void SwapControlVisibleDelegate(Control^ target);

public ref class Form1 : public System::Windows::Forms::Form
{
  /*Ctor and InitializeComponents for Form1*/
  /*...*/

  protected : 
    virtual void OnShown(EventArgs^ e) override
    {
        __super::OnShown(e);
        some_function();
    }


    void some_function()
    {
        System::Threading::Thread^ t1;
        System::Threading::ThreadStart^ ts = gcnew ystem::Threading::ThreadStart(this, &Form1::ThreadProc);
        t1 = gcnew System::Threading::Thread(ts);
        t1->Start();

    }

    void ThreadProc()
    {
        Threading::Thread::Sleep(2000);
        for each(Control^ c in this->Controls)
        {
            SwapVisible(c);
        }
    }


    void SwapVisible(Control^ c)
    {
        if(c->InvokeRequired) // If this is not a safe thread...
        {
            c->Invoke(gcnew SwapControlVisibleDelegate(this, &Form1::SwapVisible), (Object^)c);
        }else{
            c->Visible ^= true;
        }
    }
}

这是如何将方法控件调用到安全线程中以进行更改。现在我已经阅读了你对这个问题的评论。看一下BackgroundWorker 组件,它非常适合运行具有取消支持的异步任务,并且它还实现了接收有关任务进度和结束的通知的事件。

于 2012-09-24T06:42:43.457 回答