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 に答える