Delete Link followed by LoadProperty causes Cross-Thread access exception

Unanswered Delete Link followed by LoadProperty causes Cross-Thread access exception

  • Tuesday, March 20, 2012 5:22 PM
     
     

    I am trying to allow a user to move items between an "available" list and a "used" list. Here is some sample code:

    ComplexObject current_obj;

    ProgDataContainer context;

    Add_Button_Click

    {

    current_obj.UsedItems.Add((Item)ItemPicker.selected_item);

    context.AddLink(current_obj, "UsedItems", (Item)ItemPicker.selected_item);

    context.BeginLoadProperty(current_obj, "UsedItems", item_callback, new Object());

    }

    Remove_Button_Click

    {

    context.DeleteLink(current_obj, "UsedItems", (Item)UsedList.selected_item);

    current_obj.UsedItems.Remove ((Item)UsedList.selected_item);

    context.BeginLoadProperty(current_obj, "UsedItems", item_callback, new Object());

    }

    void item_callback(IAsyncResult result)

    {

    context.EndLoadProperty(result);;

    context.Items.BeginExecute(all_items_callback, new Object());

    }

    void all_items_callback (IAsyncResult result)

    {

    Dispatcher.BeginInvoke(delegate{

    ItemPicker.ItemSource = context.Items.EndExecute(result).Except(current_obj.Items);

    UsedList.ItemSource = current_obj.Items;});

    }

    Add_Button_Click works perfectly, however, when Remove_Button_Click is pressed an exception is thrown at EndLoadProperty in the first callback. The exception thrown is: "Unauthorized Access Exception, Invalid Cross-Thread Access".

    Any idea why this would be happening? Is there a better way to manage a many-to-many relationship and show it on screen at the same time?

    Thanks


    • Edited by LordTakkera Tuesday, March 20, 2012 5:24 PM added global variables
    •  

All Replies

  • Wednesday, April 25, 2012 10:49 PM
    Moderator
     
     

    Hi LordTakkera,

    You'll need to marshal all EndExecute or EndLoadProperty calls with  Dispatcher.BeginInvoke() method so that when the network stream is read, we have the right access. It may work for the Add case as the network dealy might be pretty small , and that is pure supposition on my part.
    Change all your End*** methods to have the Dispatcher.BeginInvoke call and this should work for you.


    Phani Raj Astoria http://blogs.msdn.com/PhaniRaj