在大多数情况下,最简单的事情就是使用Backgroundower组件的建议,我会强烈建议尽可能使用这种方法。如果出于某种原因,您无法为您的目的使用BackgroundWorker组件,例如,如果您使用.Net 1.1开发(yikes!)或者使用紧凑框架,则可能需要使用其他方法:
使用Winform控件必须避免修改最初创建控件的线程以外的任何线程上的控件。 BackgroundWorker组件可以为你处理这个问题,但是如果你不使用它,那么你可以并且应该使用System.Windows.Forms.Control类中的InvokeRequired属性和Invoke方法。下面是使用这个属性和方法的一个例子:
public partial class MultithreadingForm : Form
{
public MultithreadingForm()
{
InitializeComponent();
}
// a simple button event handler that starts a worker thread
private void btnDoWork_Click(object sender, EventArgs e)
{
Thread t = new Thread(WorkerMethod);
t.Start();
}
private void ReportProgress(string message)
{
// check whether or not the current thread is the main UI thread
// if not, InvokeRequired will be true
if (this.InvokeRequired)
{
// create a delegate pointing back to this same function
// the Invoke method will cause the delegate to be invoked on the main UI thread
this.Invoke(new Action<string>(ReportProgress), message);
}
else
{
// txtOutput is a UI control, therefore it must be updated by the main UI thread
if (string.IsNullOrEmpty(this.txtOutput.Text))
this.txtOutput.Text = message;
else
this.txtOutput.Text += "\r\n" + message;
}
}
// a generic method that does work and reports progress
private void WorkerMethod()
{
// step 1
// ...
ReportProgress("Step 1 completed");
// step 2
// ...
ReportProgress("Step 2 completed");
// step 3
// ...
ReportProgress("Step 3 completed");
}
}
优秀的...谢谢!现在我只需要等待我的日常工作,我就可以去做一些真正的编程。 – iandisme 2010-01-19 21:48:50
在Compact Framework(3.5)中执行此项工作。 – Royal 2014-07-13 14:27:55