我正在努力应对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。&lt;&gt; c_ DisplayClassa.b _8(Object state2) 在System.Threading.ThreadPool.WorkItem.WaitCallback_Context(对象状态) 在System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback回调,对象状态) 在System.Threading.ThreadPool.WorkItem.doWork(Object o) 在System.Threading.Timer.ring()
答案 0 :(得分:1)
根据您的堆栈跟踪,DownloadImageResult
访问(我假设)ItemsSource
的{{1}}属性。删除它或将其移动到ListBox
块内。
有关更具体的建议,请发布BeginInvoke
功能的完整内容。