Is it okay to have multiple Dispatcher.BeginInvoke?

Go To StackoverFlow.com

0

I am just a starter in silverlight and WCF. I came across a very good article "http://www.netfxharmonics.com/2008/11/Understanding-WCF-Services-in-Silverlight-2" by Miguel A. Castro which teaches to add the WCF manually.

In the example, it uses Dispatcher.BeginInvoke to write the text return by the service into a textblock in silverlight UI.

       AsyncCallback asyncCallBack = delegate(IAsyncResult result)
        {
            List<Person> person = ((IPersonService_list)result.AsyncState).EndGetPersonData(result);
            this.Dispatcher.BeginInvoke(delegate
            {
                spMain.Children.Add(new TextBlock
                {
                    Text = person[0].FirstName + person[0].LastName + person[0].City + person[0].State
                });

            });
        };

I need to populate more than one control using the same service. It seems I am not allow to call another function within the BeginInvoke method. Is the best way to have multiple BeginInvoke method? Will that consume a lot of resources?

Thanks,

2012-04-04 20:08
by user1298608


0

One way that would work: Build an enclosing UIElement structure in its entirety from the results of the WCF service call, then use one call to Dispatcher.BeginInvoke and add the structure to spMain UIElement. For example:

StackPanel sp = new StackPanel();
TextBlock tb1 = new TextBlock({
    Text=person[0].FirstName + person[0].LastName
});
sp.Children.Add(tb1);
TextBlock tb2 = new TextBlock({Text="AND SO ON Use this pattern to add UIElements to the stackpanel."});

sp.Children.add(tb2);

//now - add the StackPanel which holds other UIElements to spMain.

this.Dispatcher.BeginInvoke(delegate(){
    spMain.Children.Add( sp );
}); 
2012-04-05 01:08
by bperreault
Thanks, that's a great suggestion - user1298608 2012-04-05 14:07
Ads