WELCOME

This blog is where I post about my consulting work with Microsoft Technologies, and other random tidbits that don't fit in my Photo Blog or my Iraq Blog.

Wednesday, February 4, 2009

Simple Asynch Demo in Silverlight

Here's a demo that shows a very simple lambda and delegate based approach to making async calls in Silverlight.




Thanks to MichealGG for the code. See his response to my question on StackOverflow here: http://stackoverflow.com/questions/508177/implementing-a-nested-asynch-call-stack-scenario-in-net


<UserControl x:Class="SilverlightTestApp.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="White">
<TextBlock Name="ResultsTextBlock"
Width="400" Height="300"
TextWrapping="Wrap"/>
</Grid>
</UserControl>




using System;

using System.Threading;

using System.Windows;

using System.Windows.Controls;

 

 

namespace SilverlightTestApp

{

    public partial class Page : UserControl

    {

        public Page()

        {

            InitializeComponent();

 

        }

 

        private void AsynchDemo()

        {

            ResultsTextBlock.Text = "";

            ResponseWriteLine("BEGIN: AsynchDemo()");

 

            AsyncHelp(

                () => SlowDateTime("The time is now:  "),

                ex => ResultsTextBlock.Text += ex.ToString(),

                bla => ResultsTextBlock.Text += bla.ToString()

                );

            ResponseWriteLine("CALLED: SlowDateTime()");

 

            Action<string> r = ResponseWrite;

 

            for(int x = 0;x<100;x++)

            {

                AsyncHelp(

                    () => RandomSleep(x),

                    ex => ResultsTextBlock.Text += ex.ToString(),

                    r);  //use a delegate instead of a lambda expression

            }

 

            ResponseWriteLine("END: RandomSleep() x 100");

        }

 

        public string RandomSleep(int input)

        {

            Random r = new Random();

            int t = r.Next(10000);

            Thread.Sleep(t);

            return input.ToString() + "."; ;

        }

 

        public void ResponseWrite<T>(T result)

        {

            ResultsTextBlock.Text += result.ToString();

        }

        public void ResponseWriteLine<T>(T result)

        {

            ResultsTextBlock.Text += result.ToString() + Environment.NewLine;

        }

 

        public string SlowDateTime(string text)

        {

 

            Thread.Sleep(5000);

            return text + DateTimeOffset.Now.ToString();

        }

 

        public void AsyncHelp<T>(Func<T> f, Action<Exception> econt, Action<T> cont)

        {

            var t = new Thread((_) =>

            {

                try

                {

                    var res = f();

                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => cont(res));

                }

                catch (Exception ex)

                {

                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => econt(ex));

                }

            });

            t.Start();

        }

 

        private void Button_Click(object sender, RoutedEventArgs e)

        {

            AsynchDemo();

        }

    }

}

2 comments:

Eric Bowen said...

Here's a link to instructions on how to embed Silverlight in Blogger:

http://blog.figmentengine.com/2008/10/embedding-silverlight-in-blogger.html

Bobbi Perreault said...

Thanks for sharing this, it will be very useful to me. This is just what the doctor ordered for my current silverlight conversion project!