Here is a sample code with comments:
Example:
// This method can be called on Form_Load, Button_Click, etc. private void LoadData() { // Start a thread to load data asynchronously. Thread loadDataThread = new Thread(LoadDataAsync); loadDataThread.Start(); } // This method is called asynchronously private void LoadDataAsync() { DataSet ds = new DataSet(); // ... get data from connection // Since this method is executed from another thread than the main thread (AKA UI thread), // Any logic that tried to manipulate UI from this thread, must go into BeginInvoke() call. // By using BeginInvoke() we state that this code needs to be executed on UI thread. // Check if this code is executed on some other thread than UI thread if (InvokeRequired) // In this example, this will return `true`. { BeginInvoke(new Action(() => { PopulateUI(ds); })); } } private void PopulateUI(DataSet ds) { // Populate UI Controls with data from DataSet ds. }
source share