I' running a WPF application and want to do something like this:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
TextBox textBox = new TextBox();
mainGrid.Children.Add(textBox);
textBox.Text = "one";
Thread.Sleep(1000);
textBox.Text = "two";
Thread.Sleep(1000);
textBox.Text = "three";
Thread.Sleep(1000);
textBox.Text = "four";
}
}
The display doesn't load until all of this processing is complete hence I have a blank, unresponsive application till 3 seconds and a textbox with the word four after running the above code.
I had a look at the BackgroundWorker class and tried this:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// Set up background worker object & hook up handlers
BackgroundWorker backgroundWorker;
backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);
backgroundWorker.RunWorkerAsync();
}
private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
{
TextBox textBox = new TextBox();
mainGrid.Children.Add(textBox);
textBox.Text = "one";
Thread.Sleep(1000);
textBox.Text = "two";
Thread.Sleep(1000);
textBox.Text = "three";
Thread.Sleep(1000);
textBox.Text = "four";
}));
}
private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Debug.WriteLine("done");
}
Still the same behaviour. I want to run some tasks in the background/ in different threads which will make changes to the UI elements along execution and I want these changes to be reflected in the display immediately.