我正在使用WP7中的交叉線程操作。元素成功添加了ObservableCollection,但沒有顯示任何內容。數據綁定ListBox(lBox)給出:在非UI線程中填充ObservableCollection之後,WP7中的跨線程訪問無效
無效的跨線程訪問。
以下是我有:
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(對象STATE2) 在System.Threading.ThreadPool.WorkItem.WaitCallback_Context(對象狀態) 在System.Threading.ExecutionContext.Run(的ExecutionContext的ExecutionContext,ContextCallback回調,對象狀態) 在系統.Threading.ThreadPool.WorkItem.doWork(對象o) 在System.Threading.Timer.ring()
您的'fileName'變量來自哪裏並不是很明顯,所以您爲了簡潔起見刪除了一些代碼。這些代碼是否有修改集合? –
不,只有部分modyfying集合在DownloadImageResult(IAsyncResult結果)中。 – szysz3kster
任何堆棧跟蹤可用? –