Feeds:
Posts
Comments

Introduction:

As you have seen in this article Parallel.For loop in C#4.0 invokes a given instruction, passing in arguments :

  • an Integer type “from inclusive”
  • an Integer type “to exclusive”
  • a delegate for the action to be done

This is done on multiple threads.
In this article we will see a way to implement a static For method in C#2.0 having the same behavior.

First of all, let’s implementing our delegate which will be passed in parameter of our For static method.

public delegate void DelegateFor(int i);
public delegate void DelegateProcess();

Now the For static method

public class Parallel
{
   public static void For(int from, int to, DelegateFor delFor)
   {
      //step or chunck will be done as 4 by 4
      int step = 4;
      int count = from - step;
      int processCount = Environment.ProcessorCount;

      //Now let's take the next chunk 
      DelegateProcess process = delegate()
      {
         while (true)
         {
            int iter = 0;
            lock (typeof(Parallel))
            {
               count += step;
               cntMem = count;
            }
            for (int i = iter ; i < iter  + step; i++)
            {
              if (i >= to)
                return;
                delFor(i);
            }
         }
      };

     //IAsyncResult array to launch Thread(s)
     IAsyncResult[] asyncResults = new IAsyncResult[processCount];
     for (int i = 0; i < processCount; ++i)
     {
         asyncResults[i] = process.BeginInvoke(null, null);
     }
     //EndInvoke to wait for all threads to be completed
     for (int i = 0; i < threadCount; ++i)
     {
        process.EndInvoke(asyncResults[i]);
     }
  }
}

Don’t forget that a bigger step would perform the process by reducing lock waiting time. In consequence we would increase parallelism which is not a good idea because of the context changing between a thread and another one which consumes resources.

Do the call like this

class Program
{
  public static void Main(string[] args)
  {
     Parallel.For(0, 100, delegate (int i)
     {
        Console.WriteLine(i + " " + TID);
     });

     Console.Read();
   }

   public static string TID
   {
     get
     {
       return "TID = " +     System.Threading.Thread.CurrentThread.ManagedThreadId.ToString();
      }
   }
}

Or using lambda exression in C#3.0 😉

public static void Main(string[] args)
{
  Parallel.For(0, 100, (int i) => Console.WriteLine(i + " " + TID));
  Console.Read();
}

Thanks for reading !!

Introduction:

In the .Net 4.0 we can find a new class Parallel containing many static methods to help us in parallel programing. System.Threading.Parallel provides one For static method which will be the main point of this article.
As a matter of fact at the end of this article you’ll find a link redirecting you in one where we explain you how to implement this static method in C# .Net 2.0!!

Loop For in a C# 2.0 bloc code

public static void MethodWithoutParallel()
{
      List<string>lstInForLoop = new List<string>();
      for(int i =0;<20;i++)
      {
            lstInForLoop.Add(i.ToString());
            //simulate a heavy instruction
            Thread.SpinWait(10);
       }
}

Loop Parallel.For in a C#4.0 bloc code

public static void MethodWithParallel()
{
      List<string>lstInParallelLoop = new List<string>();
      Parallel.For(0, 20, (int i) =>
      {
             lstInParallelLoop.Add(i.ToString());
             //simulate a heavy instruction
             Thread.SpinWait(10);
      });
}

Now let’s compare the timing of these two methods

class Program
{
   public static void Main(string[] args)
   {
      DateTime startTime;
      TimeSpan duration;

      startTime = DateTime.Now;
      MethodWithParallel();
      duration = DateTime.Now - startTime;
      Console.WriteLine("MethodWithParallel done in {0}", duration.TotalMilliseconds + " ms");

      startTime = DateTime.Now;
      MethodWithoutParallel ();
      duration = DateTime.Now - startTime;
      Console.WriteLine("MethodWithoutParallel  done in {0}", duration.TotalMilliseconds + " ms");

      Console.Read();
    }
}

Output

with Thread.SpinWait method

Running in parallel performs processing time by half !!!
There are endeed dependencies on your hardware (according to the number of cores etc…)

However, let’s remove the Thread.SpinWait static method and run our loops again.

Output

without Thread.SpinWait method

The loop for inside MethodWithoutParallel performs better than the Parallel.For loop inside MethodWithParallel. It makes evidence that it must not be systematically used.
First of all, always find out where are the expensive instructions and if they can be perform thanks to a little step (or chunk) in your loop.

Now let’s have a look on how to provide a Parallel.For loop in C#2.0

Enjoy :)!!

The Yield keyword

Introduction:

Yield keyword is used in an iterator block to provide a value to the enumerator object or notice the end of an iteration.

yield return <expression>;
yield break;

It is very important to know that an iterator block is not a block of code which will be executed. It is a block which will be interpreted by compilator to generate some code. There will have a deeper article about iterators.

Let’s have a look on the following code:

public IEnumerable GetInt(IEnumerable<int> integers)
{
     var listInt = new List<int>();
     foreach (int item in integers)
     {
         //Simulate a long operation.
         Thread.Sleep(5000);
         listInt.Add(item);
     }
     return listInt;
}

As you can read it, we simulate a heavy operation with a Thread.Sleep method. A collection is implemented to collect all typed values,at the end, this collection and its content is returned.

So, in this case we will meet Thread.Sleep method as much that the number of iteration in a Test method call!

Now let’s use Yield keyword:

public IEnumerable GetInt(IEnumerable<int> integers)
{
      foreach (int item in integers)
      {
          //Simulate a long operation.
          Thread.Sleep(5000);
           yield return item;
      }
}

As you can read it, we simulate a heavy operation with a Thread.Sleep method but no collection class is implemented.

Here’s how would be the call method:

public void Test()
{
      int[] tabInt = new int[] { 1, 2, 3, 4, 5, 6 };
      foreach (int item in GetInt(tabInt))
      {
          if (item > 4)
          {
              Console.WriteLine(item);
              break;
          }
      }
}

We will not have to wait for the end of the iteration inside iterator of GetInt method. The current value is analysed and transmited to the current object inside the foreach of the call method Test.

When the condition is verified (item>4) we get out of the foreach loop.
In this case we won’t meet Thread.Sleep method as much that the number of iterations! No more waiting for the end of the block code iteration of GetInt method!

Thanks for reading 🙂

Introduction:

In a WinForm application we can use as much encapsulated UserControls as we want. But what would happen if one of these UserControl must communicate with another one?

Here we will have a look on 2 way to give our solution :

  1. Using Parent property of a control
  2. Using delegates and event programming

The 2nd way is much better because more portable, readable and maintainable!

In this exemple a WinForm will contain a usercontrol (UserControl1) which contains another usercontrol (UserControl2). UserControl2 contains a comboBox having a collection of colors. Choosing a color in this comboBox will change the color of the WinForm control.

Using Parent property of a control

public partial class UserControl2 : UserControl
{
    private void comboBox1_SelectedIndexChanged(object s, EventArgs e)
    {
       #region Using Parent class (bad way)
       switch (this.comboBox1.SelectedIndex)
       {
            case 0:
              //1rst Parent is GroupBox
              //2nd Parent is UserControl1
              //3rd Parent is Form
              Parent.Parent.Parent.BackColor = Color.Blue;
            break;
            case 1:
              Parent.Parent.Parent.BackColor = Color.Red;
            break;
        }
       #endregion
}

Using delegates and event programming

Declaration of our delegate, event and method caling the event

public delegate void ColorChanger(Color color);
public partial class UserControl2 : UserControl
{
    public event ColorChanger ColorChangerExecuter;
    public UserControl2()
    {
            InitializeComponent();
    }

    public void OnChangedSelectIndex(Color color)
    {
        if (this.ColorChangerExecuter != null)
            this.ColorChangerExecuter(color);
    }

The other way of implementing comboBox1_SelectedIndexChanged method

private void comboBox1_SelectedIndexChanged(object s, EventArgs e)
{
    #region Using Delegate with Event (better way)
    switch (this.comboBox1.SelectedIndex)
    {
        case 0:
               this.OnChangedSelectIndex(Color.Blue);
               break;
        case 1:
               this.OnChangedSelectIndex(Color.Red);
               break;
    }
    #endregion

And the call in the WinForm class

public partial class Form1 : Form
{
   UserControl2 uc2 = new UserControl2();
   public Form1()
   {
       InitializeComponent();
       uc2 = this.userControl11.userControl2;
       uc2.ColorChangerExecuter+=new
                            ColorChanger(uc2_ColorChangerExecuter);
  }

 private void uc2_ColorChangerExecuter(Color color)
 {
     this.BackColor = color;
 }
}

A listener has been created, and whatever happen to the comboBox, as we have implemented an event for this control, it will be automatically passed to the WinForm container.

Introduction :

Here we will see how to simply make a query in a table without worring about style case.

The solution is the KeyWord COLLATE.

As a matter of fact, if you do a query which returns all elements (by a case-unsensitive way) inside en table with a LIKE clause for example, you’ll have to use COLLATE clause. This clause must be combined with a string expression to apply a collation cast.

Here let’s choose SQL_Latin1_General_Cp437_CI_AI.
Latin1_General:  Identifying alphabet or used language for which sort are applied.
Cp437:
code page 437.
CI:
case-unsensitive.
AI:
accent unsensitive.

SELECT *
FROM TABLE
WHERE My_Field LIKE '%Calculé%'  -- means computed in French
COLLATE SQL_Latin1_General_Cp437_CI_AI;

Here’s the output :

calcule
CalCule
calculE
Calculé

Enjoy 😉

Introduction :

In a former query I had to get the identity value of the last insertion in a database table , but I didn’t get what I was waiting for!!
To simulate the situation let’s create 2 tables :

CREATE TABLE [dbo].[TABLE_1]
(
    Id [int] IDENTITY(1,1) NOT NULL,
    name [nchar](10) NULL,
    CONSTRAINT [PK_TABLE_1] PRIMARY KEY CLUSTERED ([Id] ASC)
)

CREATE TABLE [dbo].[TABLE_2]
(
    Id [int] IDENTITY(1,1) NOT NULL,
    name [nchar](10) NULL,
    CONSTRAINT [PK_TABLE_2] PRIMARY KEY CLUSTERED ([Id] ASC)
)

We will do an insertion inside TABLE_2 from a TRIGGER -> AFTER INSERT inside TABLE_1.

CREATE TRIGGER [dbo].[TR_TABLE_1] ON [dbo].[TABLE_1]
AFTER INSERT
AS
BEGIN
    INSERT INTO TABLE_2(name) VALUES ('inserted_foo')
END

We insert 4 records to get a different identity from the one of TABLE_1.
TABLE_1 has 0 record and its identity is 1 by default.
TABLE_2 has 4 records and its identity is 4.
At last we do our insertion inside TABLE_1 and we get the identity with @@identity first and scope identity().

INSERT INTO T1(name) VALUES ('foo')
PRINT @@IDENTITY
PRINT SCOPE_IDENTITY()

Result :
(1 row(s) affected)
(1 row(s) affected)
5
1

@@IDENTITY returns the last identity inserted whatever the level where this insertion was made. The SCOPE_IDENTITY () will always refer to inclusion level where this function is executed.
In conclusion, if you’re not sure of the existence of triggers underlying do prefer using SCOPE_IDENTITY() to avoid surprises.

NB : Use IDENT_CURRENT function to return the identity of the last insertion, whatever the session for a given table 🙂

SELECT IDENT_CURRENT('tableName')

Introduction :

In this demonstration we will see how to create a one way method in a WCF contract. This is used in the case when you concider that an exposed method in your service, will be running for a long time when you want to still handle your application during this moment.

For our demonstration we will concider one service which exposes a simple Select() method to provide informations about employees of a company from a database. Our client will bind its received datas in a datagridview and show them. Concidering that you know how to implement a business and mapping object layer we will not introduce the way how datas are requested in the database.

The following picture shows us the WCF concept :
WCF01
Service Side

Here’s how this type of solution is mostly organised:

Image11

The first thing that we have to define is the exposed datas.
Here we want to access to a list of employees in a database. So we implement Employe class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;

namespace Contracts.ComplexTypes
{
 [DataContract]
 public class Employe
 {
  [DataMember]
  public string FirstName
  {get;set;}
  [DataMember]
  public string LastName
  {get;set;}
 }
}

DataContract is the attribute used to expose our type Employe.
DataMember is the attribute used to exposed our properties.

When this is done, create a contract which is a C# interface ICompany. By this contract we are able to define exposed method through our simple service host console:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using Contracts.ComplexTypes;

namespace Contracts
{
 [ServiceContract]
 public interface ICompanyCallBack
 {
  [OperationContract(IsOneWay = true)]
  void Notify(List<Employe>listEmp);
 }

 [ServiceContract(CallbackContract = typeof(ICompanyCallBack))]
 public interface ICompany
 {
  [OperationContract]
  List<Employe>Select();

  [OperationContract(IsOneWay=true)]
  void SelectOne();
 }
}

ServiceContract is the attribute used to indicate that our contract has to expose defined methods inside. The OperationContract attribute define which methods will be exposed to the service.
Here we can see 2 ServiceContract :
ICompany interface implement a oneway method to tell :
“When a client is using me, he won’t be obliged to wait for a response from me!!”.
This ServiceContract has a CallBackContract which define used contract and its method to do the callback.

Now let’s implement our methods:

namespace Services
{
    public class Company : ICompany
    {
        #region ICompany Membres
        public List<Employe>Select()
        {
            return Business.BusinessData.select();
        }

        public void SelectOne()
        {
            //Simulate a long process
            System.Threading.Thread.Sleep(5000);
            List<Employe>listEmp = Business.BusinessData.select();
            ICompanyCallBack callBack = OperationContext.Current.GetCallbackChannel<ICompanyCallBack>();
            callBack.Notify(listEmp);
        }
        #endregion
    }
}

In the SelectOne() method we need to get the callback context transmitted by the client using an OperationContext.
GetCallbackChannel define the service contract ICompanyCallBack which will have to be implemented by the client to be notified.

Now let’s see the service host class and its configuration file:

namespace ClassicHost
{
   class Program
   {
     public static void Main(string[] args)
     {
       ServiceHost host = new ServiceHost(typeof(Services.Company));
       host.Open();
       Console.Write('Service host is listening...');
       Console.Read();
       host.Close();
     }
  }
}

Here’s the App.config file :
Click over me!!

Client Side

Our client is a winForm application which provide a binding between a datagridview datasource and the return of exposed oneway method SelectOne().

private void button1_Click(object sender, EventArgs e)
{
   //Note "MyEndPoint" EndPoint name in parameter of the DuplexChannelFactory constructor.
   //"This" keyWord is here to notify which class implement the
   //callback interce ICompanyCallBack
   DuplexChannelFactory<Contracts.ICompany>factory =
   new DuplexChannelFactory<Contracts.ICompany>(this,"MyEndPoint");

  //Thanks to he proxy we access to exposed method SelectOne().
   Contracts.ICompany proxy = factory.CreateChannel();
   proxy.SelectOne();
}

#region ICompanyCallBack Membres
public void Notify(List<Contracts.ComplexTypes.Employe>listEmp)
{
   //The Thread where we will called is not the Thread which has created
   //the user control, so we use the MethodInvoker to proceed.
   dataGridView1.Invoke(new MethodInvoker
            (delegate()
             {
               this.dataGridView1.DataSource = null;
               this.dataGridView1.DataSource = listEmp;
             }
            )
            );
    }
#endregion

As we have already said, the client implements ICompanyCallBack to be able to notify when the exposed method has finished to process.
The client configuration file App.config has the same EndPoint as what is defined in App.config of ClassicHost:

Click over me!!

You will be able to note that between the time you click on GetEmployeesCallBack button and the time when you receive the result, you still can handle your form(not freezed)!!!

Click here

Thanks for reading!! 😉