Uisng Visual Studio 2008。
主要表单是订阅类中的事件以报告进度。 CSVReader类中的ReportProgress事件始终为null,我似乎无法理解为什么会这样。
主要表格:
//Constructor
public CreateSQL()
{
InitializeComponent();
csvReader = new CSVReader();
}
private void btnCreateSQL_Click(object sender, EventArgs e)
{
if (backgroundWorker1.IsBusy != true)
{
backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
**csvReader.ReportProgress += new EventHandler<CSVReader.ProgressArgs>(CSVReader_ReportProgress);**
// Start the asynchronous operation.
backgroundWorker1.RunWorkerAsync();
}
}
protected void CSVReader_ReportProgress(object sender, CSVReader.ProgressArgs e)
{
// Call the UI backgroundworker
backgroundWorker1.ReportProgress(e.Percentage, e.Message);
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
DataTable dt = csvReader.ReadCSVFile(sFile, _hasHeader);
}
Class CSVReader:
public class CSVReader : IDisposable
{
// Event handler to bind to for reporting progress
public EventHandler<ProgressArgs> ReportProgress;
// Eventargs to contain information to send to the subscriber
public class ProgressArgs : EventArgs
{
public int Percentage { get; set; }
public string Message { get; set; }
}
}
public CSVReader()
{
}
public DataTable ReadCSVFile(string filename, bool headerRow)
{
using (CSVReader reader = new CSVReader(new FileInfo(filename)))
return reader.CreateDataTable(headerRow);
}
public DataTable CreateDataTable(bool headerRow)
{
// Read the CSV data into rows
List<List<object>> rows = new List<List<object>>();
List<object> readRow = null;
while ((readRow = ReadRow()) != null)
rows.Add(readRow);
// Report progress if somebody is listening (subscribed)
**if (ReportProgress != null)
{
ReportProgress(this, new ProgressArgs { Percentage = 33, Message = "Reading File" });
}**
}
如果ReportProgress事件为null,则它在上面进行了测试,并且它始终为null。 我把它放在这里只是为了让它发回一些变量,33和一个字符串,但它总是为空。
感谢所有输入!