Reputation: 1215
I am looping through a dataset in c# read from an excel file that contains X records. For testing purposes, I used Thread.Sleep() to pause the output for a second after each record is read. My understanding was that they way I wrote my loop, it should pause for 1 second then display 1 line of output (1 record), pause for 1 second, display 1 line, etc... However, when I execute the code I get a X second long pause followed by all records immediately being output to screen. Anyone know why this is happening? I inserted a breakpoint and stepped through it and everything seems to be working fine (no errors or anything). Sorry if this is a basic question but I'm a bit of green programmer.
private void ReadExcelFile()
{
string fileAndPath = fileTextBox.Text;
string fileName = Path.GetFileName(fileAndPath);
string directoryPath = Path.GetDirectoryName(fileAndPath);
var connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileAndPath + ";Extended Properties=\"Excel 12.0;IMEX=1;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text\""; ;
using (var conn = new OleDbConnection(connectionString))
{
conn.Open();
var sheets = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT * FROM [" + sheets.Rows[0]["TABLE_NAME"].ToString() + "] ";
var adapter = new OleDbDataAdapter(cmd);
var ds = new DataSet();
adapter.Fill(ds);
foreach (DataRow row in ds.Tables[0].Rows)
{
user = row.ItemArray[0].ToString();
email = row.ItemArray[1].ToString();
password = row.ItemArray[2].ToString();
Thread.Sleep(1000);
excelTextBox.Text += user + " " + email + " " + password + " " + Environment.NewLine;
}
}
}
}
Upvotes: 1
Views: 706
Reputation: 18069
Since you are running this method on the main thread (the UI's thread), the thread isn't available to process events (e.g. display updates).
You can do something similar to this to process UI messages: https://stackoverflow.com/a/3121934/38368
Or, better yet, redesign your code. E.g. use a separate thread. E.g. https://stackoverflow.com/a/1216799/38368
Upvotes: 3