处理此问题的最佳方法是将长时间运行的进程置于后台线程上。这可以通过BackgroundWorker 完成,并且是我在 Windows 应用程序中的选择。为什么?因为当通过它报告进度时(例如更改按钮的状态),它会自动处理线程切换到 UI 线程。
这是一个如何工作的例子。假设您有一个 BackgroundWorker 的私有类字段:
private BackgroundWorker _worker = new BackgroundWorker();
在构造函数中我们需要设置一些东西:
_worker.WorkerReportsProgress = true;
_worker.DoWork += DoWork;
_worker.ProgressChanged += ProgressChanged;
_worker.RunWorkerCompleted += RunWorkerCompleted;
好的,现在设置处理程序:
private void DoWork(object sender, DoWorkEventArgs e)
{
// do the work here
}
private void ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// e.UserState is a value that you can pass anything to
// like a string for a status label
// e.ProgressPercentage is an integer that you specify letting
// this event know what step the process is at - this is well
// used for a progress bar
}
private void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// e.Result is a value that you can pass anything to
// like a reference to an object with the finished product
// or whatever makes sense in your case
}
最后,要运行后台进程,只需这样做:
_worker.RunWorkerAsync();
并报告进度,在 DoWork 处理程序中,执行以下操作:
// NOTE: make sure to pass AT LEAST a value of 1 for the percentage
// or the event handler will NEVER fire. Further, someValue can be anything
// an instance of an object with data or just a string, or nothing for that
// matter - it's up to you
_worker.ReportProgress(1, someValue);