一、效果
二、代码
1.定义一个MyParam类。
文件MyParam.cs
using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Windows.Controls; namespace w { class MyParam { public TextBox txt{ set; get; } public String s { set; get; } public int x { set; get; } public void outAB() { // MyParam ss = (MyParam)s;//将Object型强制转换为MyParam型 StringBuilder sb = new StringBuilder(); int cs = 100; int i = 0; while (i < cs) { this.txt.Dispatcher.Invoke( () => { txt.Text += this.s + this.x;//ss.s??? } ); Thread.Sleep(100); i++; } } } }
2.文件MainWindow.xaml.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace w { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { MyParam a = new MyParam(); a.s = "张三"; a.x = 21; a.txt = this.txt; MyParam b = new MyParam(); b.s = "李四"; b.x = 22; b.txt = this.txt; ThreadStart startA = new ThreadStart(a.outAB); Thread thA = new Thread(startA); ThreadStart startB = new ThreadStart(b.outAB); Thread thB = new Thread(startB); thA.Start(); thB.Start(); } } }
3.文件MainWindow.xaml
<Window x:Class="w.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:w" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"> <Grid> <TextBox x:Name="txt" HorizontalAlignment="Center" Margin="0,53,0,0" Text="" TextWrapping="Wrap" VerticalAlignment="Top" Width="419" Height="285"/> <Button Content="多线程" HorizontalAlignment="Center" Margin="0,372,0,0" VerticalAlignment="Top" Height="28" RenderTransformOrigin="0.192,0.548" Width="55" Click="Button_Click"/> </Grid> </Window>