gpt4 book ai didi

c# - BackgroundWorker 慢

转载 作者:行者123 更新时间:2023-11-30 14:18:26 33 4
gpt4 key购买 nike

我正在开发一个项目 (WPF),我有一个 Datagrid 从数据库加载超过 5000 条记录,所以我使用 BackgroundWorker 来通知用户数据正在加载,但它太慢了,我需要等待将近 2分钟从数据库加载数据,相反,如果我不使用 BackgroundWorker,我只需等待 3 秒即可将数据加载到 Datagrid。

在这里,我写下了用于 BackgroundWorker 的代码片段:

   private void RunWorker()
{
worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.WorkerSupportsCancellation = true;
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
worker.RunWorkerAsync();
}



private void worker_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker senderWorker = sender as BackgroundWorker;
dc = new DataClasses1DataContext();
var query = from c in dc.Contact_DDBB_Xavis
select
new
{
c.ContactID,
c.Continent,
c.Country,
c.City,
c.PostalCode,
c.CompanyName,
c.UserCreated,
c.DateCreated,
c.UserModified,
c.DateModified
};

if (query.Count() > 0)
{

for (int i = 0; i < query.Count(); i++)
{

int progressInPercent = (int)(((decimal)(i + 1) / (decimal)query.Count()) * 100);
worker.ReportProgress(progressInPercent, i);

System.Threading.Thread.Sleep(10);
e.Result = query.ToList();

}
}
if (senderWorker.CancellationPending)
{
e.Cancel = true;
}
}

private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error == null)
{
this.dataGrid.DataContext = e.Result;

backGround.Visibility = Visibility.Collapsed;
duracel.Visibility = Visibility.Collapsed;
txtBackWORK.Visibility = Visibility.Collapsed;

}
}


private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
for (double i = 0.0; i < e.ProgressPercentage; i++)
{
duracel.pthFiller.Width = 0;
double max = 312;
max = (double)e.ProgressPercentage;

duracel.pthFiller.Width = e.ProgressPercentage * 3.12;

duracel.txtStatus.Text = e.ProgressPercentage + " %";
txtBackWORK.Text = String.Format("Loading " + e.ProgressPercentage + " %");

}
}

现在我不知道我的代码是否有问题,所以我向您请教一些如何更快地从数据库加载数据而无需等待这么长时间的建议。

感谢您的关注。

玩得开心。

干杯

最佳答案

每次调用 query.Count() 时,您都在运行另一个 SQL 查询。
您应该调用 Count() 一次,并将其存储在局部变量中。

此外,您应该只在进度实际发生变化时才调用 `ReportProgress。 (调用它 1,000 次没有意义)

关于c# - BackgroundWorker 慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4467569/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com