Hello,
You should try using the backgroundworker class to do this.
Setup a DoWork event handler and put in it the long code that your button is doing. In your code instead of updating the UI just raise an event ReportProgress and pass the data needed to update this UI.
Setup a ProgressChanged event handler. This is this event that will receive notifications from the background worker thread and in which you can safely update the UI.
Here is an example:
public Form1()
{
InitializeComponent();
backWkr.WorkerReportsProgress = true;
backWkr.ProgressChanged += backWkr_ProgressChanged;
backWkr.DoWork += backWkr_DoWork;
}
BackgroundWorker backWkr = new BackgroundWorker();
private void button1_Click(object sender, EventArgs e)
{
backWkr.RunWorkerAsync();
}
void backWkr_DoWork(object sender, DoWorkEventArgs e)
{
int percentProgress = 0;
do
{
percentProgress++;
Thread.Sleep(100);
object whatEverIsNeeded = "blah blah blah";
backWkr.ReportProgress(percentProgress, whatEverIsNeeded);
} while (percentProgress < 100 );
}
void backWkr_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
object whatEverStatepassed = e.UserState;
int percent = e.ProgressPercentage;
this.BackColor = Color.FromArgb(this.BackColor.R, this.BackColor.G, percent);
}
Valery.