0

1 つのボタンのクリック イベントで以下のコードを記述し、ProgressBar とforループを同時に連携させたいと考えています。だから最初は始めたtimer1

private void Button_Click(object sender, EventArgs e)
{
    this.timer1.Start();

    if (comboBox.SelectedIndex == 0)
    {
        TextBox.Clear();
        for (int j = 0; j < N; j++)
            for (int i = 0; i < N; i++)
            {
                TextBox.Text += array[i, j].ToString()+" , " ;
            }               
    }
}

しかし、ボタンをクリックすると、最初に TextBox が塗りつぶされ始め(forループが機能します)、次に timer1 が機能し始め、ProgressBar がインクリメントし始めます。

私は Visual Studio 2010、Windows Forms アプリケーションを使用し、以下のコードを記述しますtimer1

private void timer1_Tick(object sender, EventArgs e)
{
    this.ProgressBar.Increment(1);
}

どのようにすれば、起動と動作を同時に行うように設定できますか?

4

2 に答える 2

1

Windows Forms uses a single threaded message loop, so until your Button_Click hander has returned, the handler for the timer will not be able to run. Read up on the windows message loop to understand why.

The key here is that you should never perform long-running tasks in an event handler. You may have noticed that your window hangs until your code is running.

To get this to work, you could use a BackgroundWorker, or start a thread yourself. Also note that if you run your long-running task on another thread, it cannot access the form directly.

Check this old msdn article out.

于 2013-10-15T21:02:07.223 に答える