Silverlight中跨线程访问的问题2011-09-23 博客园 xiafan在silverlight中跨线程访问,不像在winform里有controls.invoke在里面一般的情况下使用的是Dispather.BeginInvoke但是本人还发现,用AsyncOperator或者AsynchronazationContext也可以实现上下文的转换代码如下Page.xaml<UserControl x:Class="SilverlightChat.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="White">
<Grid.RowDefinitions>
<RowDefinition Height="80" />
<RowDefinition Height="80" />
</Grid.RowDefinitions>
<TextBlock x:Name="tblTest" Text="not loaded yet" VerticalAlignment="Center" HorizontalAlignment="Center" Grid.Row="0" />
<Button x:Name="btnTest" Content="ClickMe" Height="30" Width="50" Click="btnTest_Click" Grid.Row="1" />
</Grid>
</UserControl>
Page.xaml.csusing System.Windows.Controls;
using System.Threading;
using System.ComponentModel;
namespace SilverlightChat
{
public partial class Page : UserControl
{
//private SynchronizationContext currentContext;
private AsyncOperation asyncOper;
public Page()
{
InitializeComponent();
asyncOper = AsyncOperationManager.CreateOperation(null);
//this.currentContext = SynchronizationContext.Current;
}
private void btnTest_Click (object sender, System.Windows.RoutedEventArgs e)
{
Thread t = new Thread(new ThreadStart(AcrossThread));
t.Start();
}
private void AcrossThread()
{
asyncOper.Post(result =>
{
tblTest.Text = "HasChanged";
}, null);
//currentContext.Post(result =>
//{
// tblTest.Text = "HasChanged";
//}, null);
}
}
}
从而达到跨线程访问UI的目的想请问达人。。后面两种访问具体在什么时候才会用的到。。