【发布时间】:2011-08-03 01:43:53
【问题描述】:
我正在为 WP7 中的跨线程操作而苦苦挣扎。元素已成功添加并执行 ObservableCollection,但随后没有显示任何内容。数据绑定 ListBox (lBox) 给出:
无效的跨线程访问。
这是我所拥有的:
public partial class MainPage : PhoneApplicationPage
{
private ObservableCollection<string> obrazkiFinal = new ObservableCollection<string>();
public ObservableCollection<string> ObrazkiFinal
{
get { return obrazkiFinal; }
set { obrazkiFinal = value; }
}
// Constructor
public MainPage()
{
InitializeComponent();
}
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
lBox.ItemsSource = ObrazkiFinal;
HttpWebRequest httpRequest = WebRequest.CreateHttp(@"http://website");
IAsyncResult res = httpRequest.BeginGetResponse(new AsyncCallback(RespResult),httpRequest);
}
private void RespResult(IAsyncResult respResylt)
{
var res = (HttpWebRequest)respResylt.AsyncState;
var resp = res.EndGetResponse(respResylt);
/* some parsing code */
foreach (/* found pic urls */)
{
//new httpwebrequest
HttpWebRequest picHttpRequest = WebRequest.CreateHttp(picUrl);
IAsyncResult picRes = picHttpRequest.BeginGetResponse(DownloadImageResult, picHttpRequest );
}
private void DownloadImageResult(IAsyncResult result)
{
var res = state.HttpWebRequest;
var resp = res.EndGetResponse(result);
/*some saving code*/
Dispatcher.BeginInvoke(() => { ObrazkiFinal.Add(fileName); });
}
}
}
然后在 XAML 中:
<ListBox Grid.Row="2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Height="Auto" Name="lBox">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Image Source="{Binding}"></Image>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
当然还有PhoneApplicationPage:
DataContext="{Binding RelativeSource={RelativeSource Self}}"
ObservableCollection 已成功填充到 UI 线程中,这是怎么回事?
添加了@edit 堆栈跟踪:
在 MS.Internal.XcpImports.CheckThread() 在 System.Windows.DependencyObject.GetValueInternal(DependencyProperty dp) 在 System.Windows.FrameworkElement.GetValueInternal(DependencyProperty dp) 在 System.Windows.DependencyObject.GetValue(DependencyProperty dp) 在 System.Windows.Controls.ItemsControl.get_ItemsSource() 在 myPhoneApp.MainPage.DownloadImageResult(IAsyncResult 结果) 在 System.Net.Browser.ClientHttpWebRequest.c_DisplayClassa.b_8(对象状态 2) 在 System.Threading.ThreadPool.WorkItem.WaitCallback_Context(对象状态) 在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback 回调,对象状态) 在 System.Threading.ThreadPool.WorkItem.doWork(对象 o) 在 System.Threading.Timer.ring()
【问题讨论】:
-
fileName变量的来源并不是很明显,因此为简洁起见,您删除了一些代码。这段代码是否修改了集合? -
不,唯一修改集合的部分在 DownloadImageResult(IAsyncResult 结果)中。
标签: .net windows-phone-7 user-interface asynchronous dispatcher