C#[Before 4.0] -- How to update GUI after the callback of a length computation
I would like to know the best practice to implement the follow scenarios.
public class MainWindow : Window
{
public void MainWorkflow()
{
// initiate a work-thread to run LongCompute
// when LongCompute finishes, update the corresponding GUI
// for example, change the statusbar as "Computation is done"
}
private void LongCompute()
{
// a 2-minute computation and then update member variables
// after it finishes. I expect the main thread to use the
// updated member variables to update GUI later
}
}
I am looking for a concrete good example to illustrate the best practice for this task. As we know, the work-thread should not be used to update the GUI because GUI should be updated by the thread whic开发者_运维技巧h created them. Also, I knew the following two modes:
Case I> The main thread waits for the worker thread and then update the GUI after than. For example, we can use the WaitOne method defined in AutoResetEvent in this case and it will be triggered by the Set method. But this is not a good way.
Case II> Set a callback function for the worker thread, however, the callback function is still called in the work thread which is not good for manipulating the GUI.
As @Jeff said in the comments, use a BackgroundWorker for this. You specify what function to call on the background thread, and another to call when the background work is done.
精彩评论