我想实现一种使用计算密集型方法将消息从对象传递到 UI 的方法,以便通知用户计算的状态和进度。执行此操作时,UI 应保持响应,即计算在另一个线程上执行。我读过委托、后台工作人员等,但我发现它们非常令人困惑,并且无法在我的应用程序中实现它们。这是一个简化的应用程序,其总体思路与我的应用程序相同。计算密集型方法完成后,UI 中的文本框在此处更新:
<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;
}
}
}
计算密集类:
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;
}
}
}
如何修改此代码以便在每次调用 AddText 方法时更新文本框?