How best execute query in background to not freeze application (.NET)

前端 未结 3 1375
刺人心
刺人心 2020-12-11 23:26

My WinForm apps needs to execute complex query with significant execution time, I have no influence (about 10mins) When query is executing user sees \'application not respon

相关标签:
3条回答
  • 2020-12-11 23:51

    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.

    0 讨论(0)
  • 2020-12-12 00:07

    If you are new to threads and task is simple (as it seems), you should try to use standard background worker component.

    0 讨论(0)
  • 2020-12-12 00:10

    The simplest approach here would be to do that work from a BackgroundWorker. MSDN has examples for this. This then executes on a worker thread, with events for completion/error/etc. It can also support cancel, but your operation needs to be coded to be interruptable.

    Another approach is the Task API in 4.0; but if you use this you'll need to get back to the UI thread (afterwards) yourself. With BackgroundWorker this is automatic (the events are raised on the UI thread).

    0 讨论(0)
提交回复
热议问题