在silverlight中跨線程訪問,不像在winform里有controls.invoke
在里面一般的情況下使用的是Dispather.BeginInvoke
但是本人還發(fā)現(xiàn),用AsyncOperator或者AsynchronazationContext也可以實(shí)現(xiàn)上下文的轉(zhuǎn)換
代碼如下
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.cs
using 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);
}
}
}
從而達(dá)到跨線程訪問UI的目的.
轉(zhuǎn)帖于:軟件水平考試_考試吧