尝试使用 backgroundworker 从 mdb 读取数据时出现错误
程序“[3768] BackgroundWorkerExample.vshost.exe: Managed”已退出,代码为 0 (0x0)。
没有任何其他信息或异常,我无法抓住它。这是我的代码,没有 BGW 它可以正常工作。我错过了什么吗?
namespace BackgroundWorkerExample
{
public class TestClass
{
BackgroundWorker _Worker;
public TestClass()
{
InitializeWorker();
}
public void InitializeWorker()
{
_Worker = new BackgroundWorker();
_Worker.DoWork += new DoWorkEventHandler(WorkerDoWork);
_Worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(WorkerRunWorkerCompleted);
}
private void WorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Console.WriteLine("Work completed!");
}
private void WorkerDoWork(object sender, DoWorkEventArgs e)
{
DataTable data = GetDataTable();
PrintResults(data);
}
public void Run()
{
_Worker.RunWorkerAsync();
}
public DataTable GetDataTable()
{
string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\students.mdb;";
try
{
using (OleDbConnection con = new OleDbConnection(connectionString))
{
try
{
con.Open(); // crashes here!
DataTable res = new DataTable();
string query = "SELECT * FROM students";
OleDbDataAdapter adapter = new OleDbDataAdapter(query, con);
adapter.Fill(res);
return res;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
}
}
catch (Exception e)
{
// never reaches this part
return null;
}
}
public void PrintResults(DataTable data)
{
foreach (DataRow row in data.Rows)
{
for (int i = 0; i < 5; i++)
{
Console.Write(row[i] + " ");
}
Console.WriteLine();
}
}
}
}