C# 当我切换窗口时,应用程序进入无响应模式
我开发了一个C#应用程序。在运行时,我切换到系统中的另一个窗口,然后应用程序进入无响应模式,但后台进程正在运行。。我在那个应用程序中有一个progressBar。我需要查看状态,它完成了多远C# 当我切换窗口时,应用程序进入无响应模式,c#,C#,我开发了一个C#应用程序。在运行时,我切换到系统中的另一个窗口,然后应用程序进入无响应模式,但后台进程正在运行。。我在那个应用程序中有一个progressBar。我需要查看状态,它完成了多远 progressBar1.Visible = true; progressBar1.Maximum = dt.Rows.Count; if (dt.Rows.Count > 0) {
progressBar1.Visible = true;
progressBar1.Maximum = dt.Rows.Count;
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
-----
----
-----
progressBar1.Value = i;
if (progressBar1.Value == progressBar1.Maximum - 1)
{
MessageBox.Show("Task completed");
progressBar1.Visible = false;
}
}
}
progressBar1.Visible=true;
progressBar1.最大值=dt.Rows.Count;
如果(dt.Rows.Count>0)
{
对于(int i=0;i
for循环正在冻结您的UI线程,这就是应用程序冻结的原因,因为在for循环中工作时无法重新绘制UI。我建议将您的工作转移到另一个线程,并使用后台工作人员:
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (worker, result) =>
{
int progress = 0;
//DTRowCount CANNOT be anything UI based here
// this thread cannot interact with the UI
if (DTRowCount > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
progress = i;
-----
---- //do some operation, DO NOT INTERACT WITH THE UI
-----
(worker as BackgroundWorker).ReportProgress(progress);
}
}
};
worker.ProgressChanged += (s,e) =>
{
//here we can update the UI
progressBar1.Value = e.ProgressPercentage
};
worker.RunWorkerCompleted += (s, e) =>
{
MessageBox.Show("Task completed");
progressBar1.Visible = false;
};
worker.RunWorkAsync();
BackgroundWorker-worker=新的BackgroundWorker();
worker.DoWork+=(worker,result)=>
{
int progress=0;
//DTRowCount不能是基于此处的任何UI
//此线程无法与UI交互
如果(数据行计数>0)
{
对于(int i=0;i
{
//在这里,我们可以更新UI
progressBar1.Value=e.ProgressPercentage
};
worker.RunWorkerCompleted+=(s,e)=>
{
MessageBox.Show(“任务完成”);
progressBar1.Visible=false;
};
worker.RunWorkAsync();
我在这里的目标是将这个循环卸载到另一个线程中,这将允许您的应用程序继续使用Windows消息泵并保持对用户的响应。工作线程在另一个线程上循环并执行它需要执行的操作,这无法与UI或WindowForms(我假设您使用的)交互,从而引发错误
根据Worker.ProgressChanged
事件,工作线程返回到主线程并显示进度报告,您可以从这里访问UI并更改进度条值
当工作程序完成后,它将回调到WorkerThread.RunWorkerCompleted
,您也可以从这里操作UI
编辑:Code,WorkerThread.RunWorkerCompleted to worker.RunWorkerCompleted更好地共享代码..因为有时您会覆盖
WinProc
或发生其他事件。WinForms,WPF,SL?如何/什么线程?我在应用程序中没有使用任何线程概念,但正如@HenkHolterman所说,您使用的是什么框架?WPF?银灯?WinForms?For循环将在应用程序运行时冻结它。for循环在UI线程上运行,此时使用的框架是无关的。把工作外包给一个汇报进度的后台工作人员,你就会得到你想要的结果。