Dispatcher and Multi-threading in Silverlight 3

In Silverlight 3, as with WinForms and WPF,  we need to be careful about cross thread communication. Controls instantiated in the XAML DOM belong to the UI thread and only the UI thread can update them. To see this, try updating the UI from a different thread,

public MainPage() {
    InitializeComponent();
 
    // Explicitly start a new thread,
    Thread myThread = new Thread(FillRectangle);
    myThread.Start();
}
 
void FillRectangle() {
    // Try to update the UI thread...
    MyRectangle.Fill = new SolidColorBrush(Colors.Red);
}
 

You’ll see an error like this,

Capture

To alleviate this Silverlight gives us two constructs,

1. The Dispatcher class: This class guarantees  that the code will be executed on the UI thread.

public MainPage() {
    InitializeComponent();
 
    // Explicitly start a new thread
    Thread myThread = new Thread(FillRectangle);
    myThread.Start();
}
 
void FillRectangle() {
    // Can't update the UI thread directly
    //MyRectangle.Fill = new SolidColorBrush(Colors.Red);

    // But perfectly safe to update the UI using the Dispatcher
    Dispatcher.BeginInvoke(() => MyRectangle.Fill = new SolidColorBrush(Colors.Red));
}
 

2. The BackgroundWorker class: Using this class gives you a new thread but also gives you a way to update the UI in a safe way.

public MainPage() {
    InitializeComponent();
    BackgroundWorker bg = new BackgroundWorker();

    // This method is called on the background thread
    bg.DoWork += CrossThreadUnsafe;

    // This method is called on the UI thread
    bg.RunWorkerCompleted += CrossThreadSafe;

    // Start the thread
    bg.RunWorkerAsync();
}
 
void CrossThreadUnsafe(object sender, DoWorkEventArgs e) {
    // Don't update the UI here - uncommenting will cause 'Invalid cross-thread access error'
    //MyRectangle.Fill = new SolidColorBrush(Colors.Red);
}
 
void CrossThreadSafe(object sender, RunWorkerCompletedEventArgs e) {
    // Perfectly safe to update the UI from here
    MyRectangle.Fill = new SolidColorBrush(Colors.Red);
}
 

Or if you want, write your own BackgroundWorker class.

Also, Silverlight provides a DispatcherTimer  class which is a UI-thread safe timer (as opposed to the Timer class), for an example see here.

Digg This
Advertisements

Five different ways to animate in Silverlight 3

There are a variety of ways to animate an object in Silverlight, let’s take a look at them today. For demo purposes say we’re trying to move a simple rectangle defined in xaml like this,

<Canvas x:Name="LayoutRoot" Background="White">
        <Rectangle x:Name="MyRectangle"  Canvas.Top="100" 
                   Canvas.Left="100" Height="50" Width="50" Fill="Black" />
</Canvas>
 

1. Using Storyboard.Begin():

// Animate the canvas left property
DoubleAnimation daLeft = new DoubleAnimation();
daLeft.To = 200.0;
daLeft.Duration = new Duration(new TimeSpan(0, 0, 0, 1));

// Set the storyboard target and target property
Storyboard.SetTarget(daLeft, MyRectangle);
Storyboard.SetTargetProperty(daLeft, new PropertyPath(Canvas.LeftProperty));

// Add the animation to the storyboard and start it
Storyboard st = new Storyboard();
st.Children.Add(daLeft);
st.Begin();
 

2. Using an empty Storyboard as a timer:

Storyboard emptyStoryboard = new Storyboard();

public MainPage() {
    InitializeComponent();

    emptyStoryboard.Duration = TimeSpan.FromMilliseconds(0);
    emptyStoryboard.Completed += new EventHandler(AnimateRectangle);
    emptyStoryboard.Begin();
}

void AnimateRectangle(object sender, EventArgs e) {
    // Animate the canvas left property
    MyRectangle.SetValue(Canvas.LeftProperty, 
                                (double)MyRectangle.GetValue(Canvas.LeftProperty) + 1.0);

    if ((double)MyRectangle.GetValue(Canvas.LeftProperty) > 200.0)
        emptyStoryboard.Stop();
    else
        emptyStoryboard.Begin();        
}
 

3. Using System.Windows.Media.CompositionTarget.Rendering:

public MainPage() {
    InitializeComponent();

    CompositionTarget.Rendering += new EventHandler(AnimateRectangle);
}

void AnimateRectangle(object sender, EventArgs e) {
    // Animate the canvas left property
    MyRectangle.SetValue(Canvas.LeftProperty, 
                                (double)MyRectangle.GetValue(Canvas.LeftProperty) + 1.0);

    if ((double)MyRectangle.GetValue(Canvas.LeftProperty) > 200.0)
        MyRectangle.SetValue(Canvas.LeftProperty, 200.0);
}
 

4. Using a System.Windows.Threading.DispatcherTimer:

private DispatcherTimer Timer = new DispatcherTimer();

public MainPage() {
    InitializeComponent();

    Timer.Interval = TimeSpan.Zero;
    Timer.Tick += new EventHandler(AnimateRectangle);
    Timer.Start();
}

void AnimateRectangle(object sender, EventArgs e) {            
    // Animate the canvas left property, this is UI-thread safe            
    MyRectangle.SetValue(Canvas.LeftProperty, 
                                (double)MyRectangle.GetValue(Canvas.LeftProperty) + 1.0);

    if ((double)MyRectangle.GetValue(Canvas.LeftProperty) > 200.0)
        Timer.Stop();
}

 

5. Using a System.Threading.Timer:

Timer Timer = null;

public MainPage() {
    InitializeComponent();
    Timer = new Timer(Animate, null, 0, 1); 
}

void Animate(object state) {
    // This is required because the Animate method is called on a different thread than the UI
    Dispatcher.BeginInvoke(new Action(AnimateRectangle));
}

void AnimateRectangle() {
    // Animate the canvas left property 
    MyRectangle.SetValue(Canvas.LeftProperty, 
                                (double)MyRectangle.GetValue(Canvas.LeftProperty) + 1.0);

    if ((double)MyRectangle.GetValue(Canvas.LeftProperty) > 200.0)
        Timer.Dispose();
} 
Digg This

Changing the namespace of a Silverlight 3 project (in VS2008)

Say you want to change the namespace of your Silverlight 3 app (this should work for Silverlight 2 too) from the default,

namespace SilverlightApplication1
to,
namespace My.Silverlight.Prototypes.Demo
 

Then the changes you need to make in the code are,

1. Change the namespace in App.xaml.cs and in App.xaml change the x:Class,

<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
             x:Class="My.Silverlight.Prototypes.Demo.App">
 

2. Change the namespace in MainPage.xaml.cs and in MainPage.xaml change the x:Class,

<UserControl x:Class="My.Silverlight.Prototypes.Demo.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="400" Height="300">
 

3. Trying to run the app now will result in an error,

Error: Sys.InvalidOperationException: InitializeError error #2103 in control ‘Silverlight1’: Invalid or malformed application: Check manifest

4. This is because the startup object is wrong, right-click the SilverlightApplication1 and select ‘Properties’, and make sure the ‘Startup object’ is set to ‘My.Silverlight.Prototypes.Demo.App’.

Properties

5. Everything should run now, though I recommend changing the assembly name, default namespace, and xap file name,

PropertiesII

6. If you follow step 5, don’t forget to change your aspx/html page to point to the new xap file,

<asp:Silverlight ID="Silverlight1" runat="server" Source="~/ClintBin/My.Silverlight.Prototypes.Demo.xap" 
MinimumVersion="3.0.40307.0" Width="100%" Height="100%" />

 

else, you’ll get the following error, because the aspx page couldn’t find the xap file.

Error: Sys.InvalidOperationException: InitializeError error #2104 in control ‘Silverlight1’: Could not download the Silverlight application. Check web server settings

Note: If your Silverlight content doesn’t show up in your aspx/html page after step 6, make sure you Clean and Rebuild your Silverlight application and regenerate your xap file by deleting it.

Digg This

Top 5 signs that your Agile/Scrum project has a problem…

A lot of teams are following Agile development with Scrum or some variant thereof. Here’s a handy list to check if your project has a problem,

5. Your burn-down chart looks like a dead person’s ECG.

4. Only chickens come to your daily standup meetings.

3. You have two sprints a year.

2. The product owner and scrum master have a cage fight during the review meetings, and everyone cheers.

And the number 1 sign that your Agile project has a problem,

1. Your team has a good laugh when the ‘potentially shippable’ clause is mentioned.

Digg This

New Features in C# Part III (C# 4.0)

[Related Posts: Part I (C# 2.0) and Part II (C# 3.0)]

(Based on the draft version of the C# 4.0 specification which are subject to change.)

Just like previous releases of C# had a major theme (think generics for C# 2.0 and LINQ for C# 3.0), the new major theme for this release is to add dynamic programming features to the C# language.

1. Dynamic lookup: A new type has been introduced called dynamic. The idea is that you can call any operation on the dynamic type you want, the compiler won’t check it at compile-time, but figure it out at runtime. A dynamic object is assumed to support any operation at compile-time, only at runtime will you get an error. The result of any dynamic operation is of type dynamic.

        // Instantiation
        dynamic d = 7; // implicit conversion
        dynamic d = GetObject();
 
        // Operations on dynamic types
        d.f = d.P;           // getting and settings fields and properties
        d[“one”] = d[“two”]; // getting and setting thorugh indexers
        int i = d + 3;       // calling operators
 

2. Named and optional parameters: Now declare optional parameters simply by providing a default value for it. And call params by name: like so,

        // Definition of the method
        public void Method(int x, int y = 1, int z = 2){}

        // Using the optional params
        Method(1);          // same as Method(1, 1, 2);
        Method(1, 2);       // same as Method(1, 2, 2);
        Method(1, 2, 3);

        // Named params called, note arbitrary order and missing y
        Method(z: 1, x: 2);
 

3. Improvements to COM interoperability: A bunch of changes to facilitate COM interop has been introduced, like passing values to reference params. Unlike in C#, COM APIs use ref params simply as a way to pass value type and make no assumptions  about mutability. Thus, specifically for COM methods we are allowed to do this,

        // For this COM method signature,
        void Method(ref int i, ref int j) { }

        // Previously we would have to do this,
        int x = 0;
        int y = 0;
        Method(x, ref y);

        // Now we can pass in y
        Method(x, y);  // But note that changes to x inside the method will be discarded.
                       // Changes to y will be retained.
 

4. Covariance and contravariance of generics: Covariance allows casting of generic types to the base types, for example, IEnumerable<A> will be implicitly convertible an IEnumerable<B> if A can implicitly be converted to B.

        // Say we have a List of strings
        IList<string> strings = new List<string>();

        // We can now convert it into an Enumerable collection
        IEnumerable<object> objects = strings;
 

For this IEnumerable will be marked with the out modifier in C# 4.0,

        public interface IEnumerable<out T> : IEnumerable {
            IEnumerator<T> GetEnumerator();
        }
 

Contravariance allows for example, IComparer<A> to be cast to IComparer<B> even if B is a derived type of A. For this IComparer will be marked with the in modifier.

        public interface IComparer<in T> {
            public int Compare(T left, T right);
        }

Digg This

New Features in C# Part II (C# 3.0)

[Related Posts: Part I (C# 2.0) and Part III (C# 4.0)]

C# 3.0 introduces some important changes to the language (like LINQ), and some cosmetic changes designed to make coding simpler and more readable. Here are some of the new changes in C# 3.0,

1. Implicitly typed local variables and arrays:  A new keyword is introduced called var. This allows you to declare a variable and let the compiler figure out the type

        // Declare a variable of type int
        var i = 5;

        // Declare an int array
        var a = new[] { 1, 10, 100, 1000 };

        // Usage:
        for (var i = 0; i < 5; i++) { }
        foreach (var item in MyList) { }
        using (var file = new StreamReader("Filename.txt")) { }
 

2. Auto-implement properties: Use this when no additional logic is required in the property accessors.

        // Previously we had to do this,
        private string _name;
        public string Name
        {
            get { return this._name; }
            set { this._name = value; }
        }
 
        // Now we can shorthand it, there’s no need to declare the _name variable
        public string Name { get; set; } // The compiler creates a private anonymous backing field
 

3. Object and collection initializers: Set properties inline during object creation.

        public class A {
            public string Name { get; set; }
            public string Address { get; set; }
        }
 
        // Previously we would have to do,
        A a = new A();
        a.Name = "...";
        a.Address = "...";

        // Now we can do this,
        A a = new A { Name = "...", Address = "..." };

        // Similarly, we can initialize collections,
        List<int> MyList = new List<int> { 0, 1, 2, 3, 4 };
 

4. Extension methods: Now you can add methods to existing types without creating a new derived type, recompiling or modifying the original type’s code. This is incredibly useful in writing cleaner code,

        // Previously we would do this,
        String domain = GetDomain(url); // url is a string type

        // Now we can do this,
        String domain = url.GetDomain();  // String now has a custom method ...

        // ... because we defined an extension method for the string type,
        public static class MyStringExtensions {
            public static String GetDomain(this String str)
            {
                // Extract domain from url and return;
            }
        }

5. Anonymous types: If you need a small class with read only properties, you can now use a simple syntax,

        // a is an anonymous type, the compiler creates the class with 
        // private string fields _name and _address 
        // and public string properties Name and Address,
        var a = new { Name = "...", Address = "..." };

        // a.Name and a.Address are read-only,
        string s = a.Name;
 

6. Lambda expressions: A new operator => is introduced called “goes to”. The left side of the operator specifies an input param and the right side is the expression or statement block.

        // A delegate can be initialized with a lambda expression
        MyDelegate d = () => { /* Do Work */ };
 

7. Query keywords (LINQ): We are now able to use TSQL like syntax inside C# to query data sources (could be objects, collections, XML, or SQL databases). Introduces a host of new keywords like from, where, select, group, orderby, join, etc.

        // The data source,
        int[] numbers = { 0, 1, 2, 3, 4, };

        // Create the query,
        var lessthan3 =
            from num in numbers
            where num < 3
            select num;

        // Output: 0 1 2
        foreach (var m in lessthan3) {
            Console.Write(m.ToString() + " ");
        }
 

8. Partial method definitions: A partical class (introduced in C# 2.0, see here) can now have partial methods. This simply means the method signature is in one partial class and the implementation in another. There are some constraints, like the method is implicitly private (and therefore cannot be virtual) and must return void.

        public partial class A {
            // Method definition
            partial void Method();
        }

        public partial class A {
            // Method implementation
            partial void Method() { /* Do Work */ }
        }

Digg This

New Features in C# Part I (C# 2.0)

I was researching new C# 4.0 features and thought about aggregating C# 2.0 and C# 3.0 features for completeness,

1. Generics: This is the major addition to the C# language in the 2.0 release. Usually when we define a type, we work with a lot of other types. What generics allows us to do is let the client code specify what types our class with work with.

        // Define type A
        public class A {
            string s;   // Requires type string
            public void Method(string s) { this.s = s; }    // Only works with type string!
        }

        // Change to a generic type
        public class A<T> {
            T t;    // Type will be set by client
            public void Method(T t) { this.t = t; }     // Works with any type!
        }

 

Generics are specifically useful in building custom collections. This is due to two reasons,

  • Your collection class can work with different types, that is, it could be a collection of ints or a collection of strings, the client can decide this without you having to change any code.
  • You don’t incur the penalties of boxing/unboxing.

        // When you put anything into an ArrayList it gets boxed into an object
        ArrayList a = new ArrayList();

        // Adding an int to this List will not cause boxing!
        List<int> b = new List<int>(); 
 
2. Iterators: Easily enable the useful foreach construct for your custom collection. Note the new yield keyword, when the yield return statement is reached, the current location is stored. Execution is restarted from this location the next time the iterator is called.
        public class DaysOfTheWeek : System.Collections.IEnumerable {
            string[] m_Days = { "Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat" };

            public System.Collections.IEnumerator GetEnumerator() {
                for (int i = 0; i < m_Days.Length; i++) yield return m_Days[i];
            }
         }
        // Usage:
        DaysOfTheWeek week = new DaysOfTheWeek();
        foreach (string day in week) { }
 
3. Partial Classes: Allows you to split a single type into multiple type definitions.
        // Before we had to do this,
        public class A
        {
            public void MethodA() { }
            public void MethodB() { } 
        }

        // Now we can construct the class in parts,
        public partial class A
        {
            public void MethodA() { }
        }

        public partial class A
        {
            public void MethodB() { }
        }

4. Nullable Types: Value-type variables can now be assigned the value null.

        int? i = 0;

        i = null;   // allowed to set int to null!

        // Usage:
        int j = i.GetValueOrDefault();
        // or,
        if (i.HasValue) k = i.Value;

    ?? operator:
        int m = i ?? -1;    // if i is null, set m to -1

 
5. Anonymous Methods: Anywhere you need a delegate (that encapsulates a method), you can now simply insert the method body. Anywhere a delegate is expected, a code block can be used instead: there is no need to define a new method.
        // If we have a delegate,
        delegate void MyDelegate();
 
        // Previously we would have to use a named method,
        MyDelegate d = a.MethodB;
 
        // Now we can use an anonymous method,
        MyDelegate d = delegate() { /* Do work; */ };
 
6. Static Classes: A static class

  • cannot be instantiated
  • cannot be inherited from (they are sealed)
  • can contain one parameterless static constructor (no instance constructors)
  • can contain only static methods.
        static class A {
            static A() { }
            public static void MethodA() { }
            public static void MethodB() { }
        }
 
7. External Assembly Alias (extern keyword): Now import C++ dlls!
        [DllImport("User32.dll")]
        public static extern int MessageBox(int h, string m, string c, int type);
 
8. Property Accessor Accessibility: Now get and set on the same property can have different accessability.

        public string Name
        {
            public get { return name; }
            protected set { name = value; }
        }
 

9. Covariance and Contravariance in Delegates
     Covariance: Return type can now be a derived class, that is, a delegate that encapsulates a method with return type A can also encapsulate a method that returns any derived type of A.
     Contravariance: Params can now be a base class, that is, a delegate that encapsulates a method that takes a param of type B can also excapsulate a method that takes a param that is a base type of B.
        // Say B derives from A,
        public class B : A { }

        
        // If we have a delegate that returns type A,
        delegate A MyDelegate(B b);

        // It can also encapsulate a method that returns B (dervied class)
        // Even though the delegate signature says that the return type should be A
        MyDelegate m = MethodThatReturnsTypeB;  // Covariance!

        // It can also encapsulate a method with a param A (base class)
        // Even though the delegate signature says that param should be type B
        MyDelegate n = MethodWithParamTypeA;  // Contravariance!

 
10. Simplified use of Delegates
  • No need to construct a delegate object explicitly,
        // Previously
        MyDelegate d = new MyDelegate(a.Method);

        // Now 
        MyDelegate d = a.Method;

  • Define a method inline,
        Thread t = new Thread(delegate(Object obj) { /* Do Work */ });

  • If params are not used,
        Thread t = new Thread(delegate { /* Do Work */ });
 
11. Friend Assemblies: An assembly can give access to its internal types/members via the InternalsVisibleToAttribute attribute. Note that private types/members remain private.
        // Mark class A with this attribute, so that B can access internal types/members
        [assembly: InternalsVisibleTo("B")]

 

12. Inline warning control: A new preprocessor directive has been added to enable/disable compiler warnings.       
        // No need for the CS prefix
        #pragma warning disable 414, 3021

Digg This