您将在 UI 的单独线程中运行长时间运行的进程以防止它挂起,BackgroundWorker
例如可能会使用 a:-
bgWorker.RunWorkerAsync([DATA TO PROCESS])//Passing in data to operate on
private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
MyObject obj = (MyObject)sender;
//
// Do some work with the data on the server
//
// Report on progess, is it done?
bgWorker.ReportProgress();
}
你也可以有一个工作完成方法
private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//Work is complete, notify user
}
您也可以使用ThreadPool,这需要更多设置,但我发现它更灵活。例如: -
ThreadPool.QueueUserWorkItem(new WaitCallback(DoWork), [DATA TO PROCESS]);
Interlocked.Increment(ref workItems);
workItems 将是剩余要处理的项目数的计数,这可用于跟踪任务是否完成。然后我们定义一个DoWork
方法来处理数据并减少我们的 workItems 计数器。处理完项目后,我们会通过代表报告进度,例如:-
private delegate void ThreadDone(MyObject obj);
private delegate void TaskDone();
public void DoWork(object sender)
{
MyObject obj = (MyObject)sender;
this.Invoke(new ThreadDone(ReportProgress), result);
Interlocked.Decrement(ref workItems);
if (workItems == 0)
{
this.Invoke(new TaskDone(WorkComplete));
}
}
报告进度可能如下所示:-
private void ReportProgress(MyObject obj)
{
if (workItems >= 0)
{
//Job isn't complete, report progress
}
}
private void WorkComplete()
{
}