[英]Problem with BackgroundWorker
我已經編寫了這段代碼,以從Excel文件中讀取數千行並將其加載到DataGridView中。
但我遇到的問題是,無論我加載哪個文件,DataGridView只顯示第一個文件中的行,而且_list永遠不會被清除。
public class MyForm : Form
{
private List<Student> _list = null;
private void LoadFile_Click(object sender, EventArgs e)
{
try
{
if (_list != null)
{
_list.Clear();
}
openFileDialog1.ShowDialog();
_connStr = MakeConnectionString.GetConnectionString(openFileDialog1.FileName);
if (!string.IsNullOrEmpty(_connStr))
{
backgroundWorker1.RunWorkerAsync();
}
}
catch
{
MessageBox.Show("Application is busy with the first task!", "Busy...", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
return;
}
IDataReader read = StudentDA.GetReader(_connStr);
List<Student> localList = null;
if (_list != null)
{
_list.Clear();
}
_list = StudentMapper.GetStudents(read);
localList = new List<Student>(_list);
dataGridView1.Invoke(new MethodInvoker(delegate
{
dataGridView1.Rows.Clear();
}));
foreach (Student std in localList)
{
dataGridView1.Invoke(new MethodInvoker(delegate
{
dataGridView1.Rows.Add(std.SerialNo, std.RollNo);
}));
}
}
}
每次加載新數據時,請嘗試創建新的BackgroundWorker對象。
您不改變_connection對象
static _connection = null;
if(_connection == null)
{
}
這僅在第一次和下一次更改文件時有效,該連接不會更改。
您確定某個地方沒有異常嗎? 嘗試處理完成事件,並檢查event-arg對象公開的異常
也; 在每個步驟中只有一個Invoke的循環可能會使速度變慢; 也許在后台進行數據獲取,然后在一個Invoke中完成整個清除/添加循環。 如果那太多了,至少把它分成小套; 或者考慮虛擬模式(對於大數據量來說效率更高)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.