winform 多线程 progressbar
小弟这两天才开始学winform,发现在winform程序UI界面使用progressbar控件时,UI就死在那里了,在网上查说要用多线程来做,就是不知道具体怎么做。谁能给个简单的例子,实现点击Button之后progressbar开始显示进度,但winform窗体不要卡死,能拖动。小弟先谢过了。
------解决方案--------------------
有些测试的代码,没有删,不好意思。
进度条的页面代码:这个是单独页面。上面有一个进度条和一个LABEL
public partial class ProgressDlg : Form
{
public ProgressDlg()
{
InitializeComponent();
}
public void OnProgressChanged(object sender, ProgressChangedEventArgs e)
{
// show the progress.
this.progressBar.Value = e.ProgressPercentage;
this.label1.Text = e.ProgressPercentage.ToString();
}
public void OnCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// thread is completed, close the dialog.
this.progressBar.Value = 100;
this.Close();
}
public CancelEventHandler OnCancel = null;
private void btnCancel_Click(object sender, EventArgs e)
{
// thread is cancelled, close the dialog.
this.Close();
}
private void ProgressDlg_FormClosed(object sender, FormClosedEventArgs e)
{
// cast notification of cancellation.
if (this.OnCancel != null)
this.OnCancel(this, new CancelEventArgs());
}
}
主界面的代码:此页面上有一个TEXTBOX,label和一个button.
public partial class Form1 : Form
{
private BackgroundWorker _backworker = null;
public Form1()
{
InitializeComponent();
this._backworker = new BackgroundWorker();
// it's neccessary to set the properties.
this._backworker.WorkerReportsProgress = true;
this._backworker.WorkerSupportsCancellation = true;
this._backworker.DoWork += new DoWorkEventHandler(backworker_DoWork);
this._backworker.ProgressChanged += new ProgressChangedEventHandler(backworker_ProgressChanged);
this._backworker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backworker_RunWorkerCompleted);
}
// body of thread
void backworker_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(100);
// trigger the event: ProgressChanged
this._backworker.ReportProgress(i);
// if receive the notification of Cancel.
if (this._backworker.CancellationPending)
{
e.Cancel = true;
return;
}
}
}
void backworker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// to do nothing.
}
void backworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// if thread is completed because of cancellation.
if (e.Cancelled)
this.labelSummary.Text = "Calculation is cancelled";
this.btnCalculate.Enabled = true;
}
void backworker_OnCancel(object sender, CancelEventArgs e)
{
this._backworker.CancelAsync();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
string temp = this.txtMax.Text.Trim();
if (string.IsNullOrEmpty(temp))
MessageBox.Show("Please input a valid integer.", "Validation", MessageBoxB