I'm struggling with cross thread operations in WP7. Elements are successfully added do ObservableCollection but then nothing is displayed. Data binded ListBox (lBox) gives:
Invalid cross-thread access.
Here is what I have:
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); });
}
}
}
And then in 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>
and of course in PhoneApplicationPage:
DataContext="{Binding RelativeSource={RelativeSource Self}}"
ObservableCollection is succesfully populated within UI thread, so what's the matter?
@edit stack trace added:
at MS.Internal.XcpImports.CheckThread() at System.Windows.DependencyObject.Ge开发者_运维技巧tValueInternal(DependencyProperty dp) at System.Windows.FrameworkElement.GetValueInternal(DependencyProperty dp) at System.Windows.DependencyObject.GetValue(DependencyProperty dp) at System.Windows.Controls.ItemsControl.get_ItemsSource() at myPhoneApp.MainPage.DownloadImageResult(IAsyncResult result) at System.Net.Browser.ClientHttpWebRequest.<>c_DisplayClassa.b_8(Object state2) at System.Threading.ThreadPool.WorkItem.WaitCallback_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadPool.WorkItem.doWork(Object o) at System.Threading.Timer.ring()
According to your stack trace, the DownloadImageResult
accesses the ItemsSource
property of (I'm assuming) your ListBox
. Remove this or move it to within a BeginInvoke
block.
For more specific advice, please post the full content of your DownloadImageResult
function.
精彩评论