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 which 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.

-------------Problems Reply------------

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.

Category:c# 3.0 Views:10 Time:2011-05-28
Tags: c# 3.0

Related post

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.187 (s). 11 q(s)