How best execute query in background to not freeze application (.NET)
If ExecuteQuery
if the method you want to execute, you can do:
void SomeMethod() {
var thread = new Thread(ExecuteQuery);
thread.Start();
}
void ExecuteQuery() {
//Build your query here and execute it.
}
If ExecuteQuery
receives some parameters, like:
void ExecuteQuery(string query) {
//...
}
You can do:
var threadStarter = () => { ExecuteQuery("SELECT * FROM [Table]"); };
var thread = new Thread(ThreadStarter);
thread.Start();
If you want to stop the execution of the background thread, avoid calling thread.Abort()
method. That will kill
the thread, and you do not want this, because some incosistency could appear in your database.
Instead, you can have a bool
variable visible from ExecuteQuery
and from outside you can set it to True
when you want to stop it. Then all you have to do is check in some parts of the code inside ExecuteQuery
if that variable is still True
. Otherwise, do some rollback to maintain the database stable.
Be sure you set that bool
variable volatile
Edit:
If you want the UI to wait from the background thread, I usually do:
- Start the background thread
- Start some progress bar in the UI
- Disable some controls (like buttons, etc) to avoid the user to click them while the background thread is working (eg: If you're executing the thread when a user clicks a button, then you should disable that button, otherwise multiple queries will be ocurring at the same time).
After finished the thread, you can stop progress bar and enable controls again.
How to know when the thread finished? You can use Events for that. Just create an event and fire it when it finishes, and do whatever you want inside the event handler...
Be sure you're accessing correctly to UI controls from the background thread, otherwise it will give you an error.
Connecting to SQL Server without freezing WPF
Appears thread blocks longer when you try opening connection while providing wrong credentials. try using await con.OpenAsync();
instead to free up UI thread.
Autocomplete textbox freezes while executing query. Must be a better way!
This line:
var result = SearchUnderlyings(e.SearchText);
Runs synchronously, locking the UI thread. The way to cure this would be to switch to an asynchronous pattern, where you start the query, and then do something when it finishes.
This article demonstrates it pretty nicely, and shows some solutions - http://www.codeproject.com/KB/cs/AsyncMethodInvocation.aspx
How to avoid freezing the browser when doing long-running computations in Javascript
If you only need to do a calculation and don't need to access the DOM during the long running calculation, then you have two options:
- You can break the calculation up into pieces and do a piece at a time on a
setTimeout()
. On eachsetTimeout()
call, the browser will be free to serve other events and will keep the page alive and responive. When you finish the last piece of the calculation, you can then carry out the result. - You can run the calculation in the background using a webworker in modern browsers. When the calcuation is done in the webworker, it sends a message back to the main thread and you can then update the DOM with the result.
Here's a related answer that also shows an example: Best way to iterate over an array without blocking the UI
.NET DB Query Without Allocations?
You cannot reuse IDataReader
(or OdbcDataReader
or SqlDataReader
or any equivalent class). They are designed to be used with a single query only. These objects encapsulate a single record set, so once you've obtained and iterated it, it has no meaning anymore.
Creating a data reader is an incredibly cheap operation anyway, vanishingly small in contrast to the cost of actually executing the query. I cannot see a logical reason for this "no allocations" requirement.
I'd go so far as to say that it's very nearly impossible to rewrite a library so as to allocate no memory. Even something as simple as boxing an integer or using a string variable is going to allocate some memory. Even if it were somehow possible to reuse the reader (which it isn't, as I explained), it would still have to issue the query to the database again, which would require memory allocations in the form of preparing the query, sending it over the network, retrieving the results again, etc.
Avoiding memory allocations is simply not a practical goal. Better to perhaps avoid specific types of memory allocations if and when you determine that some specific operation is using up too much memory.
Related Topics
How to Extract Values from Column and Update Result in Another Column
How to Skip Comma from CSV Using Double Quotes
How Best Execute Query in Background to Not Freeze Application (.Net)
Running Sum in Access Query with Group By
Performance Tuning on Inner Join with Between Condition
Using Dates from Cell or Named Range in SQL Query
How to Fill Missing Dates and Values in Partitioned Data
Dynamic Table Name in Select Statement
Select Unique Column Names from a List of Joined Tables
Want a Stored Procedure for Comma Seperated String Which Is of a Column (Has 20000 Rows ) in a Table
Postgres Column Does Not Exist
Delete Records Which Are Considered Duplicates Based on Same Value on a Column and Keep the Newest