如果有一段WPF程序:
XAML:
逻辑很简单,这段程序在点击Button之后TextBlock会显示“hellow world!”,但是如果我把程序用Task变一下,然它变成异步模式执行:
就会出现跨线程操作异常,因为
Task.Factory.StartNew(Action a) 会创建一个Task,这个Task运行在另外一个不同于UI的线程上。解决方法也很简单,就是我提到的用Dispatcher.BeginInvoke
That is..
XAML:
<Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <Grid> <Button Content="Button" HorizontalAlignment="Left" Margin="34,30,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1" x:Name="buton1"/> <TextBlock HorizontalAlignment="Left" Margin="58,90,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" x:Name="textBlock1"/> </Grid> </Window>
Code Behind:
private void Button_Click_1(object sender, RoutedEventArgs e) { this.textBlock1.Text = "hello world!"; }
逻辑很简单,这段程序在点击Button之后TextBlock会显示“hellow world!”,但是如果我把程序用Task变一下,然它变成异步模式执行:
private void Button_Click_1(object sender, RoutedEventArgs e) { Task.Factory.StartNew(() => this.textBlock1.Text = "hello world!"); }
就会出现跨线程操作异常,因为
Task.Factory.StartNew(Action a) 会创建一个Task,这个Task运行在另外一个不同于UI的线程上。解决方法也很简单,就是我提到的用Dispatcher.BeginInvoke
private void Button_Click_1(object sender, RoutedEventArgs e) { Task.Factory.StartNew(() => this.buton1.Dispatcher.BeginInvoke(new Action(() => this.textBlock1.Text = "hello world!"))); }
That is..