Show Loading animation during loading data in other thread - c#

I have an application running with the database. When I load a tables in the datagridview, my form freezes. How to ensure the smooth load animation during loading tables?
I run two threads for animation and load data into the tables, but the animation still does not always work.
private volatile bool threadRun;
private void UpdateTab()
{
// Create panel for animation
Panel loadingPanel = new Panel();
// Label, where the text will change
Label loadingLabel = new Label();
loadingLabel.Text = "Loading";
loadingPanel.Controls.Add(loadingLabel);
this.Controls.Add(loadingPanel);
// thread loading animation
threadRun = true;
Task.Factory.StartNew(() =>
{
int i = 0;
string labelText;
while (threadRun)
{
Thread.Sleep(500);
switch (i)
{
case 0:
labelText = "Loading.";
i = 1;
break;
case 1:
labelText = "Loading..";
i = 2;
break;
default:
labelText = "Loading...";
i = 0;
break;
}
loadingLabel.BeginInvoke(new Action(() => loadingLabel.Text = labelText));
}
});
// thread update DataGridView
Thread update = new Thread(ThreadUpdateTab);
update.Start();
}
private void ThreadUpdateTab()
{
// SQL Query...
myDataGridView1.Invoke(new Action(() => myDataGridView1.DataSource = myDataSet1.Tables[0]));
// ...
myDataGridView10.Invoke(new Action(() => myDataGridView10.DataSource = myDataSet10.Tables[0]));
threadRun = false;
}

When the form is frozen, it means the UI thread is too busy and so even if you try to show a loading animation, it will not animate. You should load data asynchronously.
You can have an async method which returns Task<DataTable> like the GetDataAsync method which you can see in this post. Then call it in an async event handler. In the event handler, first show the loading image, then load data asynchronously and then hide the loading image.
You can simply use a normal PictureBox showing a gif animation as loading control. Also you may want to take a look at this post to show a transparent loading image.
public async Task<DataTable> GetDataAsync(string command, string connection)
{
var dt = new DataTable();
using (var da = new SqlDataAdapter(command, connection))
await Task.Run(() => { da.Fill(dt); });
return dt;
}
private async void LoadDataButton_Click(object sender, EventArgs e)
{
loadingPictureBox.Show();
loadingPictureBox.Update();
try
{
var command = #"SELECT * FROM Category";
var connection = #"Your Connection String";
var data = await GetDataAsync(command, connection);
dataGridView1.DataSource = data;
}
catch (Exception ex)
{
// Handle Exception
}
loadingPictureBox.Hide();
}

Related

Display real progress of loading WPF DataGrid instead of .IsIndeterminate

I have managed to get ProgressBar into my WPF form. However my current skill is stuck on using:
ProgressBar.IsIndeterminate = true;
DataGrid1.ItemsSource = await GetDataAsync();
ProgressBar.IsIndeterminate = false;
Any professional ready to describe how to get ProgressBar to display actual loading progress?
Here is my full code:
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
try
{
ProgressBar.IsIndeterminate = true;
DataGrid1.ItemsSource = await GetDataAsync();
ProgressBar.IsIndeterminate = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private Task<DataView> GetDataAsync()
{
return Task.Run(() =>
{
string connectionStringDE = "Driver={Pervasive ODBC Client Interface};ServerName=DE875;dbq=#DEDBFS;Uid=DEUsername;Pwd=DEPassword;";
string queryStringDE = "select NRO,NAME,NAMEA,NAMEB,ADDRESS,POSTA,POSTN,POSTADR,COMPANYN,COUNTRY,ID,ACTIVE from COMPANY";
string connectionStringFR = "Driver={Pervasive ODBC Client Interface};ServerName=FR875;dbq=#FRDBFS;Uid=FRUsername;Pwd=FRPassword;";
string queryStringFR = "select NRO,NAME,NAMEA,NAMEB,ADDRESS,POSTA,POSTN,POSTADR,COMPANYN,COUNTRY,ID,ACTIVE from COMPANY";
DataTable dataTable = new DataTable("COMPANY");
// using-statement will cleanly close and dispose unmanaged resources i.e. IDisposable instances
using (OdbcConnection dbConnectionDE = new OdbcConnection(connectionStringDE))
{
dbConnectionDE.Open();
OdbcDataAdapter dadapterDE = new OdbcDataAdapter();
dadapterDE.SelectCommand = new OdbcCommand(queryStringDE, dbConnectionDE);
dadapterDE.Fill(dataTable);
}
using (OdbcConnection dbConnectionFR = new OdbcConnection(connectionStringFR))
{
dbConnectionFR.Open();
OdbcDataAdapter dadapterFR = new OdbcDataAdapter();
dadapterFR.SelectCommand = new OdbcCommand(queryStringFR, dbConnectionFR);
var newTable = new DataTable("COMPANY");
dadapterFR.Fill(newTable);
dataTable.Merge(newTable);
}
return dataTable.DefaultView;
});
}
You can't display the actual process unless you know it and you don't unless the API that you are using actually reports the current progress to you.
The OdbcCommand API doesn't so you should stick to using indeterminate progress bars.

populate datagridview with thread c#

Im trying to populate a datagridview from a query of sql but it takes a long time , what im trying to do is show a .gif "loading" meanwhile is populating the grid, im using threads but the .gif freezes , and if I use the CheckForIllegalCrossThreadCalls = false; the datagridview doesnt load the scroll bar acts weird. here is my code
delegate void CambiarProgresoDelegado();
BUTTON CLICK
private void btn_busca_Click(object sender, EventArgs e)
{
pictureBox1.Visible = true;
thread= new Thread(new ThreadStart(ejecuta_sql));
thread.Start();
}
method
private void ejecuta_sql()
{
if (this.InvokeRequired)
{
CambiarProgresoDelegado delegado = new CambiarProgresoDelegado(ejecuta_sql);
object[] parametros = new object[] { };
this.Invoke(delegado, parametros);
}
else
{
myConnection.Open();
SqlCommand sql_command2;
DataSet dt2 = new DataSet();
sql_command2 = new SqlCommand("zzhoy", myConnection);
sql_command2.CommandType = CommandType.StoredProcedure;
sql_command2.Parameters.AddWithValue("#FechaIni", dateTimePicker1.Value.ToShortDateString());
sql_command2.Parameters.AddWithValue("#FechaFin", dateTimePicker2.Value.ToShortDateString());
SqlDataAdapter da2 = new SqlDataAdapter(sql_command2);
da2.Fill(dt2, "tbl1");
grid_detalle.DataSource = dt2.Tables[0];
myConnection.Close();
pictureBox1.Visible = false;
}
and the .gif freezes until the thread finish his job.
You created a thread but then immediately made the code switch back to the main UI thread with Invoke(), negating any benefits of making the thread in the first place.
Run the query on the other thread, then Invoke() just the part that updates the UI:
private string FechaIni;
private string FechaFin;
private void btn_busca_Click(object sender, EventArgs e)
{
btn_busca.Enabled = false;
pictureBox1.Visible = true;
FechaIni = dateTimePicker1.Value.ToShortDateString();
FechaFin = dateTimePicker2.Value.ToShortDateString();
thread = new Thread(new ThreadStart(ejecuta_sql));
thread.Start();
}
private void ejecuta_sql()
{
myConnection.Open();
SqlCommand sql_command2;
DataSet dt2 = new DataSet();
sql_command2 = new SqlCommand("zzhoy", myConnection);
sql_command2.CommandType = CommandType.StoredProcedure;
sql_command2.Parameters.AddWithValue("#FechaIni", FechaIni);
sql_command2.Parameters.AddWithValue("#FechaFin", FechaFin);
SqlDataAdapter da2 = new SqlDataAdapter(sql_command2);
da2.Fill(dt2, "tbl1");
myConnection.Close();
this.Invoke((MethodInvoker)delegate {
grid_detalle.DataSource = dt2.Tables[0];
pictureBox1.Visible = false;
btn_busca.Enabled = true;
});
}
You may consider changing your approach, especially if you are doing a lot of GUI updates from your background threads. Reasons:
UI update takes time and it slows down background processing as you have to lock
too many updates coming from the background threads will overwhelm the UI and might cause freezes.
you probably don't want to update GUI every millisecond or so
What I prefer is to do polling the background thread data instead. Set up GUI timer for say 300ms, then check if there is any data ready to be updated, then do quick update with proper locking.
Here is code example:
private string text = "";
private object lockObject = new object();
private void MyThread()
{
while (true)
{
lock (lockObject)
{
// That can be any code that calculates text variable,
// I'm using DateTime for demonstration:
text = DateTime.Now.ToString();
}
}
}
private void timer_Tick(object sender, EventArgs e)
{
lock(lockObject)
{
label.Text = text;
}
}
Note, that while the text variable is updated very frequently the GUI still stays responsive. If, instead, you update GUI on each "text" change, your system will freeze.

c# threads and cannot call invoke

I have start c# a few time ago, so there is somethings that are totally diferent from java, a few time ago I face a problem about a thread changing the UI (add rows to a DataGridView) and I found that I had to call the method Invoke to make that happen. I did and all works fine, but now I'm facing a new problem. So, I have a frame that will display some labels added dynamically and in Java i would like this:
Thread t = new Thread() {
public void run() {
while (true) {
// for each label
for (it = labels.iterator(); it.hasNext();) {
JLabel lb = it.next();
if (lb.getLocation().x + lb.getWidth() < 0) {
if (msgsRemover.contains(lb.getText().toString())) {
it.remove();
MyPanel.this.remove(lb);
msgsRemover.remove(lb.getText().toString());
} else {
// if there is no message to be removed, this will just continue
// going to the end of the queue
MyPanel.this.remove(lb);
MyPanel.this.add(lb);
}
MyPanel.this.repaint();
MyPanel.this.validate();
}
lb.setLocation(lb.getLocation().x - 3, 0);
}
MyPanel.this.repaint();
try {
SwingUtilities.invokeAndWait(running);
sleep(30);
} catch (InterruptedException ex) {
Logger.getLogger(MyPanel.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(MyPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
};
But in C# I have a problem when the thread does:
MyPanel.this.remove(lb);
MyPanel.this.add(lb);
So I did:
if (lb.Location.X + lb.Width < 0) {
if (msgsRemover.Contains(lb.Text.ToString())) {
labels.Remove(label);
this.Invoke(new MethodInvoker(() => { this.Controls.Remove(lb); }));
msgsRemover.Remove(lb.Text.ToString());
} else {
// if there is no message to be removed, this will just continue
// going to the end of the queue
this.Invoke(new MethodInvoker(() => { this.Controls.Remove(lb); }));
this.Invoke(new MethodInvoker(() => { this.Controls.Add(lb); }));
}
this.Invoke(new MethodInvoker(() => { this.Refresh(); }));
But know I'm getting an error called "Can not call Invoke or BeginInvoke on a control until the window handle has been created."
I have searched for solutions but I didn't find out what can I do to solve this.
Thank you in advance for your help!
Edit: start the thread is the last thing I do in the constructor... There is the code:
public MyPanel(Color corLabel, Color back, Font text){
this.color = corLabel;
this.backg = back;
this.textFont = text;
this.Width = 500000;
texto = new LinkedList<string>();
msgs = new LinkedList<MensagemParaEcra>();
labels = new LinkedList<Label>();
var it = labels.GetEnumerator();
var it2 = msgsRemover.GetEnumerator();
this.FlowDirection = FlowDirection.LeftToRight;
this.BackColor = backg;
this.Size = new Size(500000, 30);
this.Refresh();
startThread();
}
You must start the thread after the control has a handle created in order to be able to do Invoke, the easiest way to do that is override the OnHandleCreated method and start your thread there instead.
public MyPanel(Color corLabel, Color back, Font text)
{
this.color = corLabel;
this.backg = back;
this.textFont = text;
this.Width = 500000;
texto = new LinkedList<string>();
msgs = new LinkedList<MensagemParaEcra>();
labels = new LinkedList<Label>();
var it = labels.GetEnumerator();
var it2 = msgsRemover.GetEnumerator();
this.FlowDirection = FlowDirection.LeftToRight;
this.BackColor = backg;
this.Size = new Size(500000, 30);
this.Refresh();
}
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
startThread();
}
The error you are receiving indicates that the target Window hasn't fully created yet. Probably the constructor hasn't finished. Try to hook up to one of the default events (Load, Show etc.) of the target window and make the invoke calls after these are handled.

Want to use Task Parallel Library with progress reporting for updating database

i developed a application where multiple connection string are stored. i just iterate in for loop and connect each db and execute sql against each db. in this way i update multiple database with bulk sql statement.
Now i need to use now Task Parallel Library to update multiple db simultaneously instead of updating one after one in loop. i also want to handle exception and also want to show multiple progress bar for multiple database operation. pause & resume functionality should be there.
when i will click on button then multiple db connection will be open and for each task a new progress bar will be added in my form. each progress bar will show each db operation progress. when any task will be finish then that corresponding progress bar will be removed from form.
any one can guide me with sample code how to do it using TPL.
here i got one code which update one progressbar but i need to update multiple progress bar.
int iterations = 100;
ProgressBar pb = new ProgressBar();
pb.Maximum = iterations;
pb.Dock = DockStyle.Fill;
Controls.Add(pb);
Task.Create(delegate
{
Parallel.For(0, iterations, i =>
{
Thread.SpinWait(50000000); // do work here
BeginInvoke((Action)delegate { pb.Value++; });
});
});
UPDATE Question
i did it in this way. code works but all progress bar value increase sequentially.
i have one form and one user control in winform apps. please have a look at my code and tell me what is wrong there.
main for code
public partial class Main : Form
{
public Main()
{
InitializeComponent();
this.DoubleBuffered = true;
}
private void btnStart_Click(object sender, EventArgs e)
{
Progress ucProgress = null;
Dictionary<string, string> dicList = new Dictionary<string, string>();
dicList.Add("GB", "conn1");
dicList.Add("US", "conn2");
dicList.Add("DE", "conn3");
fpPanel.Controls.Clear();
Task.Factory.StartNew(() =>
{
foreach (KeyValuePair<string, string> entry in dicList)
{
ucProgress = new Progress();
ucProgress.Country = entry.Key;
ucProgress.DBConnection = entry.Value;
fpPanel.BeginInvoke((MethodInvoker)delegate
{
fpPanel.Controls.Add(ucProgress);
ucProgress.Process();
});
//fpPanel.Controls.Add(ucProgress);
System.Threading.Thread.SpinWait(5000000);
}
});
}
private void Main_Resize(object sender, EventArgs e)
{
this.Invalidate();
}
private void Main_Paint(object sender, PaintEventArgs e)
{
using (LinearGradientBrush brush = new LinearGradientBrush(this.ClientRectangle,
Color.WhiteSmoke,
Color.LightGray,
90F))
{
e.Graphics.FillRectangle(brush, this.ClientRectangle);
}
}
}
user control code
public partial class Progress : UserControl
{
public Progress()
{
InitializeComponent();
lblMsg.Text = "";
pbStatus.Minimum = 0;
pbStatus.Maximum = 100;
}
public string Country { get; set; }
public string DBConnection { get; set; }
public string Sql { get; set; }
public void SetMessage(string strMsg)
{
lblMsg.Text = strMsg;
}
public void Process()
{
var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
Task.Factory.StartNew(() =>
{
lblMsg.BeginInvoke((MethodInvoker)delegate
{
lblMsg.Text = "Connecting country " + Country;
});
pbStatus.BeginInvoke((MethodInvoker)delegate
{
pbStatus.Value = 30;
});
System.Threading.Thread.SpinWait(50000000);
//***********
lblMsg.BeginInvoke((MethodInvoker)delegate
{
lblMsg.Text = "executing sql for country " + Country;
});
pbStatus.BeginInvoke((MethodInvoker)delegate
{
pbStatus.Value = 60;
});
System.Threading.Thread.SpinWait(50000000);
//***********
lblMsg.BeginInvoke((MethodInvoker)delegate
{
lblMsg.Text = "sql executed successfully for country " + Country;
});
pbStatus.BeginInvoke((MethodInvoker)delegate
{
pbStatus.Value = 100;
});
System.Threading.Thread.SpinWait(50000000);
});
//System.Threading.Thread.SpinWait(50000000); // do work here
}
}
perhaps it can be starting point. Handling pause/resume depends from your needs and can be tweaked.
var cancellationTokenSource = new CancellationTokenSource();
var cancellation = cancellationTokenSource.Token;
void UpdateDatabases(IEnumerable<...> databases, CancellationToken cancellation)
{
foreach(db in databases)
{
//create as many ProgressBar instances as databases you want to update
//check if ProgressBar exist, then return it and reuse, otherwise create new
ProgressBar pb = new ProgressBar();
pb.Maximum = iterations;
pb.Dock = DockStyle.Fill;
Controls.Add(pb);
//start thread for every database/progress bar
Task.Factory.StartNew(progressBar =>
{
var start = (ProgressBar)progressBar).Value; //use last value in case of pause
Parallel.For(start, iterations,
new ParallelOptions(){CancellationToken = cancellation}
(i, loopState) =>
{
if (loopState.ShouldExitCurrentIteration)
return;
//perhaps check loopState.ShouldExitCurrentIteration inside worker method
Thread.SpinWait(50000000); // do work here
BeginInvoke((Action)delegate { ((ProgressBar)progressBar).Value++; });
});
},
pb, cancellation)
.ContinueWith(task =>
{
//to handle exceptions use task.Exception member
var progressBar = (ProgressBar)task.AsyncState;
if (!task.IsCancelled)
{
//hide progress bar here and reset pb.Value = 0
}
},
TaskScheduler.FromCurrentSynchronizationContext() //update UI from UI thread
);
}
}
//.........
//Call
UpdateDatabases(databases, cancellation)
//To suspend, call
cancellationTokenSource.Cancel();
//To resume - simply call UpdateDatabases again
cancellationTokenSource = new CancellationTokenSource();
cancellation = cancellationTokenSource.Token;
UpdateDatabases(databases, cancellation)
Update
I've reviewed your code. Take a look at the revisited code and adapt it to your needs. Main mistakes - mess with closures and creating the Progress from non-ui thread. To enable parallel processing you can use Parallel.ForEach (see MSND for possible overloads). Also the design looks little bit strange for me(you're mixing data and logic in the Progress ). From UI perspective it's also strange that progress bars will appear in order of processing but not in original order as they are in list (it will be a problem if you decide to sort the list alphabetically)
I hope it help.
main for code
private void btnStart_Click(object sender, EventArgs e)
{
Progress ucProgress = null;
Dictionary<string, string> dicList = new Dictionary<string, string>();
dicList.Add("GB", "conn1");
dicList.Add("US", "conn2");
dicList.Add("DE", "conn3");
fpPanel.Controls.Clear();
Func<KeyValuePair<string, string>, object> createProgress = entry =>
{
var tmp = new Progress {Country = entry.Key, DBConnection = entry.Value};
fpPanel.Controls.Add(tmp);
return tmp;
};
Task.Factory.StartNew(() =>
{
//foreach (KeyValuePair<string, string> entry in dicList)
Parallel.ForEach(dicList,
entry =>
{
//create and add the Progress in UI thread
var ucProgress = (Progress)fpPanel.Invoke(createProgress, entry);
//execute ucProgress.Process(); in non-UI thread in parallel.
//the .Process(); must update UI by using *Invoke
ucProgress.Process();
System.Threading.Thread.SpinWait(5000000);
});
});
}
user control code
public void Process()
{
//uiScheduler - Not used
//var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
//The Task is not necessary because the Process() called from Parallel.ForEach
//Task.Factory.StartNew(() =>
//{
//BeginInvoke or Invoke required
lblMsg.BeginInvoke((MethodInvoker)delegate
{
lblMsg.Text = "Connecting country " + Country;
});
pbStatus.BeginInvoke((MethodInvoker)delegate
{
pbStatus.Value = 30;
});
System.Threading.Thread.SpinWait(50000000);
//***********
lblMsg.BeginInvoke((MethodInvoker)delegate
{
lblMsg.Text = "executing sql for country " + Country;
});
pbStatus.BeginInvoke((MethodInvoker)delegate
{
pbStatus.Value = 60;
});
System.Threading.Thread.SpinWait(50000000);
//***********
lblMsg.BeginInvoke((MethodInvoker)delegate
{
lblMsg.Text = "sql executed successfully for country " + Country;
});
pbStatus.BeginInvoke((MethodInvoker)delegate
{
pbStatus.Value = 100;
});
System.Threading.Thread.SpinWait(50000000);
//});
//System.Threading.Thread.SpinWait(50000000); // do work here
}

C# Thread dataGridView and Loading

Im trying to load a dataGridView which takes some time, so ive come up with an idea of hiding the datagridview and put an image over the top which says Loading... when finished, the image goes away and the datagrid reappears. Ive tried to do this using threading but having no luck.
Can somebody tell me if i am approaching this in the right way?
Label loadingText = new Label();
PictureBox loadingPic = new PictureBox();
private void TelephoneDirectory_Load(object sender, EventArgs e)
{
dataGridView1.Visible = false;
Thread i = new Thread(LoadImage);
i.Start();
Thread t = new Thread(LoadData);
t.Start();
}
void LoadImage()
{
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(LoadImage));
}
else
{
loadingPic.Image = Properties.Resources.ReportServer;
loadingPic.Location = new Point(0, 0);
loadingPic.Name = "loadingPic";
loadingPic.Dock = DockStyle.Fill;
loadingPic.SizeMode = PictureBoxSizeMode.CenterImage;
loadingText.Text = "Loading, please wait...";
loadingText.Name = "loadingText";
loadingText.TextAlign = ContentAlignment.MiddleCenter;
loadingText.Size = new Size(this.Size.Width, 30);
loadingText.Font = new System.Drawing.Font("Segoe UI", 9);
loadingText.Location = new Point(0, (this.Size.Height / 2 + 10));
this.Controls.AddRange(new Control[] { loadingPic, loadingText });
loadingText.BringToFront();
}
}
private void LoadData()
{
if (dataGridView1.InvokeRequired)
{
dataGridView1.Invoke(new MethodInvoker(this.LoadData));
}
else
{
DirectorySearcher sea = null;
DirectoryEntry dir = null;
DirectoryEntry d = null;
string domainname = System.DirectoryServices.ActiveDirectory.Domain.GetComputerDomain().Name;
domainname = domainname.Replace(".", ",DC=");
try
{
dir = new DirectoryEntry();
dir.Path = "LDAP://DC=" + domainname;
sea = new DirectorySearcher(dir);
sea.Filter = "(&(objectClass=user)(extensionAttribute1=1)(telephoneNumber=*))";
sea.PageSize = 2000;
SearchResultCollection res = sea.FindAll();
foreach (SearchResult result in res)
{
//DO ALL MY STUFF
dataGridView1.Rows.Add(row);
}
}
catch { }
LoadDataComplete();
}
}
void LoadDataComplete()
{
PictureBox loadingGraphic = this.Controls["loadingPic"] as PictureBox;
Label LoadingLabel = this.Controls["loadingText"] as Label;
DataGridView dataGrid = this.Controls["dataGridView1"] as DataGridView;
dataGrid.Visible = true;
LoadingLabel.Visible = false;
LoadingLabel.Dispose();
loadingGraphic.Visible = false;
loadingGraphic.Dispose();
dataGridView1.Sort(dataGridView1.Columns[0], ListSortDirection.Ascending);
dataGridView1.ClearSelection();
}
Spawning threads for this might not be the best idea, you could use ThreadPool or BackgroundWorker
Loading image should be fast enough that you could just do it synchronously, so make sure you actually need to do some operation on the other thread before you actually need it.
Ask yourself questions like: what if actually my image will load later then my dataTable? ("but it loads faster every time I checked" is not an valid argument when talking about threads)
At the beginning of your methods you are using .Invoke which basically means "wait for UI thread and invoke my code on it synchronously" which bombards your whole idea.
Try something like this:
Load image synchronously
Use ThreadPool to load your DataTable in it, but without using .Invoke
When it's loaded and you need to interact with UI -> then put your code in .Invoke()
Pseudocode coud look like this:
private void TelephoneDirectory_Load(object sender, EventArgs e)
{
dataGridView1.Visible = false;
LoadImage();
ThreadPool.QueueUserWorkItem(new WaitCallback(o => LoadData()));
}
void LoadData()
{
//...Do loading
//but don't add rows to dataGridView
if (dataGridView1.InvokeRequired)
{
//Invoke only the ui-interaction code
dataGridView1.Invoke(new MethodInvoker(this.LoadDataComplete));
}
}
void LoadDataComplete()
{
foreach (SearchResult result in res)
{
//DO ALL MY STUFF
//If do all my stuff is compute intensive and doesn't require UI,
//put it before Invoke() (like here)
dataGridView1.Rows.Add(row);
}
//Rest of code
}

Categories

Resources