【问题标题】:Invalid cross-thread access in WP7 after populating ObservableCollection within non UI thread在非 UI 线程中填充 ObservableCollection 后,WP7 中的跨线程访问无效
【发布时间】: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


【解决方案1】:

根据您的堆栈跟踪,DownloadImageResult 访问(我假设)您的ListBox 的ItemsSource 属性。删除它或将其移动到 BeginInvoke 块内。

如需更具体的建议,请发布您的DownloadImageResult 函数的完整内容。

【讨论】:

  • 太好了,感谢您的帮助。 ObservableCollection 和 ListBox 一切正常。我试图访问 IsolatedStorageFile.GetUserStoreForApplication();在 Dispatcher 之外。
  • @szysz3kster 这听起来不像是问题的真正原因。 Isolaed Storage 可从任何线程使用,而不仅仅是 UI 线程。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多