I would like to implement a way to pass messages to the UI from an object with computationally intensive methods in order to inform the user of the status and progress of the computations. While doing this the UI should remain responsive, i.e. the computations are performed on another thread. I've read about delegates, backgroundworkers and so on, but I find them very confusing and have not been able to implement them in my application. Here is a simplified application with the same general idea as my application. The textbox in the UI is here updated after the computationally intensive method is completed:
<Window x:Class="UpdateTxtBox.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="UpdateTxtBox" Height="350" Width="525">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="1*" />
</Grid.ColumnDefinitions>
<Button Content="Start" Height="23" HorizontalAlignment="Left" Margin="94,112,0,0" Name="btnStart" VerticalAlignment="Top" Width="75" Click="btnStart_Click" />
<TextBox Grid.Column="1" HorizontalAlignment="Stretch" Margin="0,0,0,0" Name="txtBox" VerticalAlignment="Stretch" TextWrapping="Wrap" VerticalScrollBarVisibility="Visible" />
</Grid>
namespace UpdateTxtBox
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void btnStart_Click(object sender, RoutedEventArgs e)
{
MyTextProducer txtProducer = new MyTextProducer();
txtProducer.ProduceText();
txtBox.Text = txtProducer.myText;
}
}
}
The computationally intensive class:
namespace UpdateTxtBox
{
public class MyTextProducer
{
public string myText { get; private set; }
public MyTextProducer()
{
myText = string.Empty;
}
public void ProduceText()
{
string txt;
for (int i = 0; i < 10; i++)
{
txt = string.Format("This is line number {0}", i.ToString());
AddText(txt);
Thread.Sleep(1000);
}
}
private void AddText(string txt)
{
myText += txt + Environment.NewLine;
}
}
}
How can a modify this code so that the textbox is updated each time the AddText method is called?