Thread and ProgressBar

Hi guys,

I have a problem with changing the value of the ProgressBar in a Thread method.

Here is the code.This is a simple windows form with a progress bar and a cancel button to stop the progress.

using System;

using System.Drawing;

using System.Collections;

using System.Windows.Forms;

using System.Data;

using OpenNETCF;

using OpenNETCF.Threading;

using System.Threading;

namespace ProgressBar

{

/// <summary>

/// Summary description for Form1.

/// </summary>

public class Form1 : System.Windows.Forms.Form

{

private System.Windows.Forms.ProgressBar progressBar;

private System.Windows.Forms.Button button1;

private System.Windows.Forms.Button button2;

private System.Windows.Forms.MainMenu mainMenu1;

public bool flag = false;

public int x = 0;

 

 

public Form1()

{

p = new Process();

InitializeComponent();

}

......

......
......


......

static
void Main()

{

Application.Run(new Form1());

}

private void button1_Click(object sender, System.EventArgs e)

{

run();

}

private void button2_Click(object sender, System.EventArgs e)

{

stop();

}

 

public void run()

{

ThreadEx t = new ThreadEx(new ThreadStart(loop));

this.progressBar.Minimum = 0;

this.progressBar.Maximum = 50;

t.Start();

}

 

public void stop()

{

this.flag = true;

}


public void loop()

{

while(!this.flag&&this.x<50)

{

System.Console.WriteLine("xxxxxxxx");

this.progressBar.Value++;

this.x++;

}

}

 

}

}


When it starts the thread, it will be stuck at the line ' this.progressBar.Value++;' without an error. I have tried to put the adding value statement out of the loop() method, and it works. I don't know where is the problem. Help...

Thanks,
Justin




Answer this question

Thread and ProgressBar