views:

29

answers:

2

Hi,

I'm in trouble when using the background worker to create my object model.

As I understand why, I'm unable to find a workaround.

Here is the pseudo logic :

  • Call Webservice async

  • When received, open a background worker, and load data into controls in the background

  • in the Load method, search for an existing object and if not found, create a new one.

All objects created inherits from Control (with a transparent abstract layer).

While I create controls on the main thread, the function work fine :

public static T Find<T>(ObservableCollection<T> collection, int objectId)
        where T : FormaliteBaseControl, new()
    {
        foreach (T item in collection)
        {
            if (item.ObjectId == objectId)
                return item;
        }

        return new T();
    }

Of course, when called from the background thread, a cross thread exception occurs at "new T()" In Silverlight, there is no way to call Dispatcher.Invoke synchronously.

And while I'm creating around 450 objects in this way, I would like to keep the object model creation in the Background without decreasing performance with Thread.Sleep or other "great" methods.

Thanks for your answers.

A: 

Are you creating actual UI controls? That's what I'm implying. If that's the case, it doesn't seem to make sense to delegate that to a background thread. Why? Beacuse the ultimately are UI objects, so they must be created on the UI thread. I know you're concerned about blocking, but all of your main work ends up having to be marshalled back to the UI.

Probably the best case for this will be to provide a pub/sub model. You can spawn the thread that has the logic to the background thread, but it will never instantiate an object. Instead, it will publish the request. On the UI thread, you listen and create the objects. Reactive Extensions (Rx) would be particularly useful for this because you can convert the ObservableCollection to an Observable then marshall the iterations to the UI.

Jeremy Likness
A: 

Thanks for both of you.

My controls build a treeview like. In reality, a root object contains 4 expanders, which got an itemscontrol as child (contains 45 objects). Each of theses child object got another expander with an itemscontrol, having around 10 childs.

@WPCoder: As the itemscontrol rarely contains more than 10 objects and very rarely 45, and because the items can have multiple height and child, Virtualization did'nt help me (yes, i've tried)

After some test, I see that it is the templating step which take this time. My object declaration fit in a second. So I've used a workaround to keep first deep objects collapsed when the object model become to big. The users keep the possibility to force expanding at startup as a parameter, but they know the backwards of this method.

@Jeremy, I suppose that the MVVM is the best solution to implement your solution ? I'll read for Reactive Extensions. Thanks.

Echtelion