后台工作者在c#中冻结UI [英] Background Worker freezes UI in c#
本文介绍了后台工作者在c#中冻结UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
HI ..
我正在使用后台工作程序,但它仍在Windows应用程序中冻结UI。
HI..
I'm using background-worker but still it freeze UI in windows Application.
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
try
{
Action DoCrossThreadUIWork = ()
{
CreateDataGridView(); // Method Create dataGridView and Handling Some GridView Events (e.g dataGridView1_Paint)
DayScheduleTable = clsSqlQueries.ExecuteQuery(clsSqlQueries.GetDaySchedule); // Read Table From DataBase
FillDataGridView(); // Fill DataGridView
};
this.BeginInvoke(DoCrossThreadUIWork);
}
catch (Exception ex)
{
clsWriteLog.GetInstance().WriteErrorLog(clsPublicMethod.GetInstance().GetMethodName(), ex.Message);
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
并在Form_load中调用后台工作者事件: br />
And Call background worker in Form_load Event As:
if (!backgroundWorker1.IsBusy)
backgroundWorker1.RunWorkerAsync()
如果有任何想法请分享..
If have any idea please share..
推荐答案
从一开始,我认为它悬挂的原因是因为你的进步bar可能是另一个线程所拥有的。像其他人所说,你可能想在这里重新考虑你的设计。
调用另一个线程所做的GUI元素更新的一种方法是创建一个调用者委托。以下代码说明了标签的更新方法,该标签旨在显示当前时间。
另外,个人偏好的问题是匿名线程就像松散的经典。它们非常适合执行一些非常简单的一次性操作。但如果要不断更新UI元素,我建议不要在这种情况下使用它们。
Right from the start, I think the reason it's hanging is because your progress bar is likely OWNED by another thread. Like others have stated, you might want to reconsider your design here.
A way to invoke updates to a GUI element made by another thread is to make an invoker delegate. The following code illustrates an update method to a label which is designed to display the current time.
Also, a matter of personal preference is that anonymous threads are like loose canons. They're great for executing some very simple, one-time operation. But if it's to continuously update a UI element, I'd advise against their use in this case.
private delegate void StatusCallbackString(string someText);
.
.
.
private void updateUITime(string time)
{
if (lblTime.InvokeRequired)
{
StatusCallbackString sCB = new StatusCallbackString(updateUITime);
this.BeginInvoke(sCB, new object[] { time });
return;
}
lblTime.Text = time;
}
同时,在某个地方的后台线程......
Meanwhile, in a background thread somewhere...
private void MyThreadedOperation()
{
while(keepThreadAlive)
{
updateUITime(DateTime.Now.ToString());
.
.
// Sleep nicely for 1 second...
System.Threading.CurrentThread.Join(1000);
}
}
这篇关于后台工作者在c#中冻结UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文