gpt4 book ai didi

c# - UI 对长时间的 for 循环 react 迟钝

转载 作者:行者123 更新时间:2023-11-30 20:44:40 26 4
gpt4 key购买 nike

我有一个 WinForm 应用程序,它使用 Spreadsheetlight 从 excel 文件读取数据,有一种方法可以读取信息然后进行一些计算,然后我创建一个新的 excel 文件。

问题是这个文件有大约 100,000 条记录,我在 UI 中有一个标签,我想在每次读取 excel 行时更新它,但标签似乎没有响应;

 public List<DataRow> GeExcelData(string filePath)
{
var myTable = new List<DataRow>();
int row = 0;

using (var input = new SLDocument(filePath))
{
SLWorksheetStatistics stats = input.GetWorksheetStatistics();
int iStartColumnIndex = stats.StartColumnIndex;

progressBar1.Minimum = 0;
progressBar1.Maximum = stats.EndRowIndex;
progressBar1.Step = 1;

for (row = stats.StartRowIndex + 1; row <= stats.EndRowIndex; ++row)
{
//Here is the label
lblStatus.Text = "Reading row " + row + " of " + stats.EndRowIndex;

var dataRowTmp = new DataRow()
{
name = input.GetCellValueAsString(row, iStartColumnIndex),
sku = input.GetCellValueAsString(row, iStartColumnIndex + 1),
value2 = input.GetCellValueAsString(row, iStartColumnIndex + 2),
value3 = input.GetCellValueAsString(row, iStartColumnIndex + 3)
};

progressBar1.PerformStep();
myTable.Add(dataRowTmp);
}

lblStatus.Text = "";
progressBar1.Value = 0;
}

return myTable;
}

有没有办法在执行一些长时间运行的任务时有效地更新 UI。因为只是一个标签我不想写一些复杂的代码。我还有运行良好的 progressBar1。

最佳答案

尝试这段代码,声明将在主线程上更新控件的委托(delegate)方法,查看下面的实现,

delegate void SetStatus(string value);
delegate void SetProgress(int value);

启动一个线程来处理数据和更新控件,

Thread t  = new Thread(StartProc);
t.Start();


public void StartProc()
{
using (var input = new SLDocument(filePath))
{
SLWorksheetStatistics stats = input.GetWorksheetStatistics();

int iStartColumnIndex = stats.StartColumnIndex;
for (row = stats.StartRowIndex + 1; row <= stats.EndRowIndex; ++row)
{
int percent = (row+1)*100/stats.EndRowIndex;
//Here is the label
setStatus("Reading row " + row + " of " + stats.EndRowIndex);
var dataRowTmp = new DataRow()
{
name = input.GetCellValueAsString(row, iStartColumnIndex),
sku = input.GetCellValueAsString(row, iStartColumnIndex + 1),
value2 = input.GetCellValueAsString(row, iStartColumnIndex + 2),
value3 = input.GetCellValueAsString(row, iStartColumnIndex + 3)
};
setProgress(percent);
myTable.Add(dataRowTmp);

}
setStatus("");
setProgress(0);
}
}
private void SetStatus(string value)
{
if (this.InvokeRequired)
{
SetStatusDelg dlg = new SetStatusDelg(this.SetStatus);
this.Invoke(value);
return;
}
lblStatus.Text = value;
}
private void SetProgress(int value)
{
if (this.InvokeRequired)
{
SetProgressDelg dlg = new SetProgressDelg(this.SetStatus);
this.Invoke(value);
return;
}
progressBar1.value = value;
}

关于c# - UI 对长时间的 for 循环 react 迟钝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29024974/

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