Loading data from the database asynchronously in the form of a gain

many times we fill the user interface with data from the database in the form loading, and therefore the form is delayed for several seconds. so I just want to know how I can load data asynchronously and populate the user interface in the form loading, as a result, my form will not be dependent, and will also be responsive, but I do not want to use a background working class. please help me with a sample code that can solve my problem.

thanks

+4
source share
4 answers

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. } 
+7
source
 Command.BeginExecuteReader() 

may serve as your need for reading.

Here is the sample code for this method.

You can call Application.DoEvents() , waiting for a response so that your window responds.

+2
source

Take a look at this article. http://aspadvice.com/blogs/azamsharp/archive/2007/04/05/Executing-a-Query-Asynchronously-in-.NET-2.0.aspx

It still uses a background worker. Honestly, I can’t come up with an alternative solution to this, other than flashing your application to execute queries and link the returned results. If you decide to use threads, I suggest you take a look at this article on a thread pool for asynchronous execution: http://www.yoda.arachsys.com/csharp/threads/threadpool.shtml p>

+1
source

Your best course of action is to use a different thread. You can use one straight from the thread pool by calling ThreadPool.QueueUserWorkItem .

  private void OnFormLoad() { ThreadPool.QueueUserWorkItem(() => GetSqlData()); } private object GetSqlData() { using (var connection = new SqlCeConnection("ConnectionString")) { using(var command = new SqlCeCommand()) { command.Connection = connection; command.CommandText = "SELECT * FROM tbl_hello"; command.ExecuteReader(); while (command.ExecuteReader().Read()) { //Put data somewhere } } } } 
0
source

Source: https://habr.com/ru/post/1332618/


All Articles