With the new TaskFactory class from .Net 4.0 it has become incredibly easy to manage dependencies between multiple tasks.
In below code sample, the TaskFactory receive 6 tasks to execute. Additional logic is added as:
- Task A will only be run when Task B and C are completed.
- Task C will only be run when Task F, E or D is completed.

If you are confused with the ‘=>’ have a look at lambda expression.

using System;
using System.Threading;
using System.Threading.Tasks;

namespace TasksDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            UseTask demoTask = new UseTask();
            Console.ReadKey();
        }
    }

    class UseTask
    {
        public UseTask()
        {
            // Set the TaskFactory - Create and schedule objects
            var tf = new TaskFactory(
                TaskCreationOptions.AttachedToParent,
                TaskContinuationOptions.AttachedToParent);

            var F = tf.StartNew(() => DoSomething(‘F’));
            var E = tf.StartNew(() => DoSomething(‘E’));
            var D = tf.StartNew(() => DoSomething(‘D’));

            // C will be started only when F, E or D has been completed
            var C = tf.ContinueWhenAny(new Task[]{F, E, D}, tasks => DoSomething(‘C’)); 

            var B = tf.StartNew(() => DoSomething(‘B’));

            // A will only happens once B and C are completed.
            var A = tf.ContinueWhenAll(new Task[] {B, C}, tasks => DoSomething(‘A’));
        }

        private void DoSomething(char @char)
        {
            Console.WriteLine(“DoSomething called - {0}”, @char);
            Random rd = new Random();
            Thread.Sleep(rd.Next(1000, 3000));
            Console.WriteLine(“DoSomething called - {0} - DONE”, @char);
        }
    }
}

 

Isn’t that beautiful?

 

 For developers the quality of a program can be often express in the time used to finish the computation. With current multicore processor we have to move our thinking from a serial execution to a concurrent execution. Using delegates in an asynchronous way can force the CLR to allocate multiple threads to your computation.

In below code sample, you will see that I call one method multiple times. This method simply waits 5 seconds. Calling 6 times this method in a synchronous way makes the time to finish obvious: at least 30 seconds! Now using the BeginInvoke method from my delegate I can add multiple threads to these computations. On my machine the time to achieve this is now 9 seconds only!

using System;
using System.Diagnostics;
using System.Text;
using System.Threading;

 

namespace Threads

{

    class Program

    {

        public delegate string myDelegate(string txt);

 

        static void Main(string[] args)

        {

            SynchronousDelegateSample();

            AsynchronousDelegateSample();

 

            Console.WriteLine(“Main thread exits.”);

            Console.ReadKey();

        }

 

        static void SynchronousDelegateSample()

        {

            Stopwatch sw = new Stopwatch();

            sw.Start();

 

            /*

             * All the calls to the delegate will be synchronous

             * This mean that the order will always be 1,2,3,4,5,6

             * The thread used will always be the same.

             */           

            myDelegate dm = new myDelegate(DelegateMethod);

            Console.WriteLine(dm(“calling delegate (1)”));

            Console.WriteLine(dm(“calling delegate (2)”));

            Console.WriteLine(dm(“calling delegate (3)”));

            Console.WriteLine(dm(“calling delegate (4)”));

            Console.WriteLine(dm(“calling delegate (5)”));

            Console.WriteLine(dm(“calling delegate (6)”));

 

            sw.Stop();

            Console.WriteLine(“All work was done in: {0} milliseconds.\n\n”, sw.ElapsedMilliseconds);

        }

 

        static void AsynchronousDelegateSample()

        {

            Stopwatch sw = new Stopwatch();

            sw.Start();

 

            /*

             * All the work will be invoked in a blink.

             * Multiple thread will be used to compute the result of the method.

             */

            myDelegate dm = new myDelegate(DelegateMethod);

            IAsyncResult result1 = dm.BeginInvoke(“calling delegate (1)”, null, null);

            IAsyncResult result2 = dm.BeginInvoke(“calling delegate (2)”, null, null);

            IAsyncResult result3 = dm.BeginInvoke(“calling delegate (3)”, null, null);

            IAsyncResult result4 = dm.BeginInvoke(“calling delegate (4)”, null, null);

            IAsyncResult result5 = dm.BeginInvoke(“calling delegate (5)”, null, null);

            IAsyncResult result6 = dm.BeginInvoke(“calling delegate (6)”, null, null);

 

            /*

             * EndInvoke is synchronous we force to wait for the asynchronous results.

             */

            string r1 = dm.EndInvoke(result1);

            string r2 = dm.EndInvoke(result2);

            string r3 = dm.EndInvoke(result3);

            string r4 = dm.EndInvoke(result4);

            string r5 = dm.EndInvoke(result5);

            string r6 = dm.EndInvoke(result6);

 

            sw.Stop();

            Console.WriteLine(“All asynchronous  work was done in: {0}”,

                sw.ElapsedMilliseconds);

        }              

 

        /// <summary>

        /// Method called by our delegate

        /// Will wait for a random time (between 1 and 10000 milliseconds).

        /// </summary>

        /// <param name=”txt”>Any string are okay.</param>

        /// <returns>A string confirming the end of the process.</returns>

        static string DelegateMethod(string txt)

        {

            // Wait 5 seconds.

            Thread.Sleep(5000);

 

            // Work is finished

            Console.WriteLine(txt + ” \n> Thread ID is: {0}”,

                Thread.CurrentThread.ManagedThreadId.ToString());

            return “>> “ + txt + ” Done !”;

        }

    }

}

Delegate can also be used to call method from different classes. I let you check at the documentation on Msdn.

 

 

This is my first post of, I hope, a series related to WPF and C#.

The examples below are made with VS (Visual Studio) 2010 and .Net 4.0, for this precise example you can make it work with .Net 3.5 at least.

During the life of an application we can listen for some important events, these events can help us to drive the logic of our application from the startup to the end of an application life.

If you are creating a simple WPF Application in VS you will get a file called App.xaml for free. In this file you can add arguments to handle events.

<Application x:Class=”WpfAppStartup.App”

             xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”

             xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”

             Startup=”Application_Startup”

             Exit=”Application_Exit”

             Activated=”Application_Activated”

             Deactivated=”Application_Deactivated”

             SessionEnding=”Application_SessionEnding”

             StartupUri=”MainWindow.xaml”>

 

As you can see in the above code, I added the Startup and Exit arguments in the Application node.
(Tip: just write ‘Startup=’ and then press Tab on your keyboard to have the method name and signature automatically created in App.xaml.cs file).

Below is the list of Events you can catch and a short description.

Name

Description

Startup

Called when Application.Run() is called, shortly before the main window is displayed. This is where you can extract all cmdline arguments.

Exit

Called when the application is shut down, shortly before the Run() methods returns.

Activated

Called when application get focus.

Deactivated

Called when application lose focus.

SessionEnding

Occurs when the Windows session is ending (log off or shut down computer).

DispatcherUnhandledException

Called when an Unhandled application occurs in your application (main thread).

 

Now back to our first goal: getting the arguments array!

private void Application_Startup(object sender, StartupEventArgs e)

{

if (e.Args.Length > 0)

       {

             foreach (string arg in e.Args)

              {

                    // logic for arguments processing.

              }

}

       else

       {

             // No arguments!

}

 

MessageBox.Show(“Application.Run() is called, “ +

“this happen before the main window is displayed.”);

}


If there are any unclear sentence, please feel free to comment!

 

In the two previous posts (Enumerate all classes from a namespace and Enumerate all Namespaces from Root) we gather enough information to enumerate namespaces and classes. In this post we are going to see how to enumerate all the instances from a class via WQL.

using System;
using System.Collections.Generic;
using System.Text;
using System.Management;

namespace WmiNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            //Represents the scoop for management operations
            ManagementScope ms = new ManagementScope();

            //Represents the management query
            ObjectQuery wql = new ObjectQuery("select * from Win32_DiskDrive");

            //Retrieve a collection of management objects
            ManagementObjectSearcher searcher =
                new ManagementObjectSearcher(ms, wql);

            //Represents different collections
            ManagementObjectCollection oc = searcher.Get();

            //The enumerator of the collection
            ManagementObjectCollection.ManagementObjectEnumerator oe =
                oc.GetEnumerator();

            Console.WriteLine("This class got " + oc.Count + " instance(s)\n");

            //Enumerate the collection
            while (oe.MoveNext())
            {
                Console.WriteLine("\n********* " +
                                  oe.Current.GetPropertyValue("Name") + "\n");

                //Foreach of the properties existing in one of our instance
                //display the propety name and her value
                foreach (PropertyData prop in oe.Current.Properties)
                {
                    Console.WriteLine("> " + prop.Name + " (" + prop.Value + ")");
                }
            }

            Console.ReadLine();
        }
    }
}

Below is a screenshot of what I get after executing this program:

wmi Class Instance Screenshoot

Next step will be to add, update or delete instance from a class.

Ahmet

 

Now that we know how to enumerate all the namespace from root, let’s have a look on how to enumerate all the classes from a namespace.

using System;
using System.Collections.Generic;
using System.Text;
using System.Management;

namespace WmiNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            //Represents the scoop for management operations
            ManagementScope ms = new ManagementScope();

            //Provides a wrapper for building paths to WMI objects
            //Here we connect to the namespace called "CIMV2"
            ManagementPath path = new ManagementPath(@"\\localhost\root\CIMV2");

            //Represents a CIM management class
            ManagementClass newClass = new ManagementClass(path);

            //Provides a base class for query and enumeration-related options objects
            EnumerationOptions options = new EnumerationOptions();

            //Return class members that are immediately related to the class
            options.EnumerateDeep = false;

            //Retrieve the  sbuclasses using the specified options
            foreach (ManagementObject o in newClass.GetSubclasses(options))
            {
                Console.WriteLine(Convert.ToString(o["__Class"]));
            }
            Console.ReadLine();
        }
    }
}

You should see this:

wmi Namespace Classes Screenshoot

Next step is to enumerate all the instances from a class.

Ahmet

 

I like to understand WMI (Windows Management Instrumentation) as a database, main concepts are:

Namespaces: Databases

Classes: Tables

Properties: Columns

Instances: Lines

Values: Fields

With this in mind, we can start enumerating all the namespaces we can access locally.

using System;
using System.Collections.Generic;
using System.Text;
using System.Management;

namespace WmiNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            //Represents the scoop for management operations
            ManagementScope ms = new ManagementScope();

            //Provides a wrapper for building paths to WMI objects
            ManagementPath path = new ManagementPath(@"\\localhost\root");
            ms.Path = path;

            ms.Connect();

            if (ms.IsConnected)
            //At this point we are connected to WMI
            {
                //Represents a management query that returns instances or classes
                ObjectQuery wql = new ObjectQuery("select * from __Namespace");

                //Retrieves a collection of
                //management objects based on the specified query
                ManagementObjectSearcher searcher =
                    new ManagementObjectSearcher(ms, wql);

                //Represents different collections
               //of management objects retrieved through WMI
                ManagementObjectCollection oc = searcher.Get();

                //Represents the enumerator on the collection
                ManagementObjectCollection.ManagementObjectEnumerator oe =
                    oc.GetEnumerator();

                while (oe.MoveNext())
                {
                    foreach (PropertyData prop in oe.Current.Properties)
                    {
                        Console.WriteLine("\t{0}", prop.Value);
                    }
                }
            }
            Console.ReadLine();
        }
    }
}

Running this program will display:

WMI Namespace Screenshoot

Next step is to enumerate all classes from a Namespace. This will come at next post :)

Ahmet