Gunnar Peipman's ASP.NET blog

ASP.NET, C#, SharePoint, SQL Server and general software development topics.

Sponsors

News

 
 
 
DZone MVB

Links

Social

May 2009 - Posts

.Net Service Bus: How to make training kit examples authenticate without problems

I’m trying out Azure Training Kit examples to study cloud stuff that should hit the streets (or sky) later this year. I faced some trouble when trying to connect with .Net Service Bus using settings mentioned in examples (netTcpRelayBinding and CardSpace). I tried hard but CardSpace authentication failed every time. My final solution was simple: I moved to username and password authentication scheme.

I found some very good information from David-Pur Maor’s blog entry Azure .NET Services – A Twitter Service Bus. There is one more reason why you should read this entry – it introduces a Twitter service bus. :)

Basically we need to change the configuration files so there is no information about authentication schemes. Service configuration file looks like this.


<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <bindings>
      <netTcpRelayBinding>
        <binding name="default" />
      </netTcpRelayBinding>
    </bindings>
 
    <services>
      <service name="Service.EchoService">
        <endpoint name="RelayEndpoint"
             contract="Service.IEchoContract"
             binding="netTcpRelayBinding"
        />
      </service>
    </services>
 
  </system.serviceModel>
</configuration>

As a next thing we have to modify Service and Client Program.cs files. You can take contents of these files with copy and paste (I made no corrections to line breaks because you anyway delete them after copying this code).

Program.cs (Service)

using System;
using System.ServiceModel;
using Microsoft.ServiceBus;
 
namespace Service
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Please enter the solution name to use in this lab: ");
            var account = Console.ReadLine();
 
            Console.Write("Please enter the solution password: ");
            var passwd = Console.ReadLine();
 
            var address = ServiceBusEnvironment.CreateServiceUri("sb", account, "EchoService");
            var host = new ServiceHost(typeof(EchoService), address);
 
            var behavior = new TransportClientEndpointBehavior();
            behavior.CredentialType = TransportClientCredentialType.UserNamePassword;
            behavior.Credentials.UserName.UserName = account;
            behavior.Credentials.UserName.Password = passwd;
 
            foreach (var endpoint in host.Description.Endpoints)
            {
                endpoint.Behaviors.Add(behavior);
            }
 
            host.Open();
            Console.WriteLine("Service address: " + address);
            Console.WriteLine("Press [Enter] to exit");
            Console.ReadLine();
            host.Close();
        }
    }
}

Program.cs (Client)


using System;
using System.ServiceModel;
 
using Microsoft.ServiceBus;
 
namespace Client
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter the name of the solution you want to connect with: ");
            var solutionName = Console.ReadLine();
            Console.Write("Please enter the solution password: ");
            var pass = Console.ReadLine();
 
            var serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", solutionName, "EchoService");
            var address = new EndpointAddress(serviceUri);
 
            var channelFactory = new ChannelFactory<IEchoChannel>("RelayEndpoint", address);
 
            var behavior = new TransportClientEndpointBehavior();
            behavior.CredentialType = TransportClientCredentialType.UserNamePassword;
            behavior.Credentials.UserName.UserName = solutionName;
            behavior.Credentials.UserName.Password = pass;
            channelFactory.Endpoint.Behaviors.Add(behavior);
 
            IEchoChannel channel = channelFactory.CreateChannel();
            channel.Open();
 
            Console.WriteLine("Enter text to echo (or [Enter] to exit):");
            var input = Console.ReadLine();
            while (!String.IsNullOrEmpty(input))
            {
                try
                {
                    Console.WriteLine("Server echoed: {0}", channel.Echo(input));
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error: " + e.Message);
                }
                input = Console.ReadLine();
            }
 
            channel.Close();
            channelFactory.Close();
        }
    }
}

David’s Twitter example code contains one more hidden gem – method you can use to let users safely insert passwords on command line. No characters are shown, only asterisks.


kick it on DotNetKicks.com pimp it Shout it
ASP.NET 4.0: Modifying ClientID of controls

Client-side ID-s of ASP.NET controls have been problem for a long time. They are hard to predict and guess. Fool-proof method that uses JavaScript block that defines client-side ID-s as variable values is not very elegant. Today’s web applications use client-size scripting heavily and now ASP.NET 4.0 provides us with elegant features to handle client-size ID-s of controls to make client-side scripting easier for us. Let’s see quick example.

To prepare the test project follow these steps:

  1. Create new web application project.
  2. Create new master page (Site1.Master).
  3. Create new content page (ContentPage.aspx) that uses previously create master page.
  4. Create new web user control (UserControl1.ascx).
  5. Add checkbox to user control and assign values to its ID and Text properties.

My pages are here. If you don’t want to copy-paste these then scroll down, right to the end of this mark-up block.

Site1.Master


<%@ Master Language="C#" AutoEventWireup="true" 
   
CodeBehind="Site1.master.cs" 
   
Inherits="WebApplicationTest.Site1" %>

<%@ Register src="UserControl1.ascx" tagname="UserControl1" 
   
tagprefix="uc1" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" 
           
runat="server">
                      
        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
</html>

ContentPage.aspx


<%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" 
   
AutoEventWireup="true" CodeBehind="ContentForm.aspx.cs" 
   
Inherits="WebApplicationTest.ContentForm" %>

<%@ Register src="UserControl1.ascx" tagname="UserControl1" 
   
tagprefix="uc1" %>
 
 
<asp:Content ID="Content1" ContentPlaceHolderID="head" 
   
runat="server">

</asp:Content>
 
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" 
   
runat="server">

 
    <uc1:UserControl1 ID="UserControl11" runat="server" />
 
</asp:Content>

UserControl1.ascx


<%@ Control Language="C#" AutoEventWireup="true" 
   
CodeBehind="UserControl1.ascx.cs" 
   
Inherits="WebApplicationTest.UserControl1" %>


<asp:CheckBox runat="server" ID="weatherCheckBox"  
   Text="Is weather nice today?"
/>

Now we have pages and user control created and it is time to run our application. When application opens in browser let’s see the source of page. Our special interest is the checkbox and how it is rendered. We should see something like this:


<input id="ctl00_ContentPlaceHolder1_UserControl11_weatherCheckBox" 
   
type="checkbox" 
   
name="ctl00$ContentPlaceHolder1$UserControl11$weatherCheckBox" 
/>
<label 
    for="ctl00_ContentPlaceHolder1_UserControl11_weatherCheckBox">
    Is weather nice today?
</label>

As we can see we have id that is hardly bound to the location of control in control tree. This is not something we want when we want client-side scripts to do something with server-side controls.

Changing ClientID of control using ClientIDMode

ASP.NET 4.0 has new attribute for controls: ClientIDMode. Using ClientIDMode attribute it is possible control how controls get their client-side ID-s. Let’s try out the following definition for checkbox.


<asp:CheckBox runat="server" ID="weatherCheckBox" 
   ClientIDMode="Static"
   Text="Is weather nice today?"
/>

As you can see I set ClientIDMode to value Static. Let’s see the ID of checkbox now.


<input id="weatherCheckBox" type="checkbox"
   
name="ctl00$ContentPlaceHolder1$UserControl11$weatherCheckBox" 
   
/><label for="weatherCheckBox">
Is weather nice today?</label>


As we can see checkbox has now both ID in server and client side, just as we wanted. The name of control is still like before but somehow ASP.NET has to know where control is located in page’s control hierarchy.

To find out more about ClientIDMode you can read ClientIDMode documentation from MSDN Library.


kick it on DotNetKicks.com vote it on Web Development Community pimp it Progg it Shout it
Posted: May 30 2009, 09:34 PM by DigiMortal | with 7 comment(s)
Filed under: ,
Reading embedded files at runtime

I have class library that contains some XML-files as embedded resources. Reading these files at runtime is very easy. It takes only couple of lines of code.

Let’s assume we have class library MyExamples.TestLibrary where we have XML-file called mappings.xml. When we compile our class library then mappings.xml will be put inside assembly as embedded resource. Here is the code to read this XML-file (you need to import System.IO, System.Reflection and System.XML namespaces).

C#
var fileName = "MyExamples.TestLibrary.mappings.xml";
var assembly = Assembly.GetExecutingAssembly();
var stream = assembly.GetManifestResourceStream(fileName);
 
if (stream == null)
{
    throw new FileNotFoundException("Cannot find mappings file.",
fileName);
}
 
var doc = new XmlDocument();
doc.Load(stream);
 
// Do something cool with embedded XML

VB.NET


Dim fileName = "MyExamples.TestLibrary.mappings.xml"
Dim assembly = Assembly.GetExecutingAssembly()
Dim stream = assembly.GetManifestResourceStream(fileName)

If stream Is Nothing Then
    Throw New FileNotFoundException("Cannot find mappings file.", _
        fileName)
End If

Dim doc = New XmlDocument()
doc.Load(stream)

' Do something cool with embedded XML

Some things to notice. If there is no resource we are asking then stream will be null. No exception will be thrown. Second thing is resource name. We don’t use only file name but also assembly name to locate the resource. If you don’t provide assembly name then resource is not found and resource stream is null.


kick it on DotNetKicks.com pimp it Shout it
Posted: May 30 2009, 11:59 AM by DigiMortal | with 9 comment(s)
Filed under:
ASP.NET 4.0 SEO features: Description and keywords

Another new SEO feature that ASP.NET 4.0 introduces is support for meta description and keywords. I think these are the most abused SEO features ever and search engines are very careful when considering these meta tags but I am very sure that there are still engines that respect those tags and that’s what makes these new features very useful.

Let’s see now how to set meta keywords and description to page. At first let’s create empty ASP.NET page and let’s see through browser the mark up of this page. Mark up should look something like this.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>
  
</title>
</head>

<body>

Now let’s write Load event for page. In this event we set meta description and keywords programmatically. Just take the following code in language you prefer.

C#
protected void Page_Load(object sender, EventArgs e)
{
    Page.MetaDescription = "This is my rabbits page";
    Page.MetaKeywords = "rabbit, rabbits, bunny, bunnies";
}

VB.NET


Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    Page.MetaDescription = "This is my rabbits page"
    Page.MetaKeywords = "rabbit, rabbits, bunny, bunnies"
End Sub

Let’s run web application again and see page source through browser again. You should see something like this.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>

</title>
<meta name="description" content="This is my rabbits page" />
<meta name="keywords" content="rabbit, rabbits, bunny, bunnies" />
</head>

<body>

There is one little thing that is annoying for me: meta tags are not splitted to separate lines. To make mark up easier to read I had to insert line breaks manually. But server-side code, as you can see, is simple and straightforward.


kick it on DotNetKicks.com vote it on Web Development Community pimp it Progg it Shout it
Posted: May 27 2009, 12:38 PM by DigiMortal | with 24 comment(s)
Filed under: ,
ASP.NET 4.0 SEO features: Response.RedirectPermanent()

ASP.NET 4.0 introduces some SEO improvements. Response has now new method called RedirectPermanent(). This method performs same redirect as Response.Redirect() but it uses response code 301. You can find more information about HTTP response codes from HTTP 1.1 specification, chapter 10. Status Code Definitions.

Response.Redirect() returns 302 to browser meaning that asked resource is temporarily moved to other location. Permanent redirect means that browser gets 301 as response from server. In this case browser doesn’t ask the same resource from old URL anymore – it uses URL given by Location header.

To illustrate difference between Response.Redirect() and Response.RedirectPermanent() let’s look at simple example. We need one usual ASP.NET Web Application with Global.asax file. In Global.asax file we have to implement BeginRequest() method.

C#
protected void Application_BeginRequest(object sender, EventArgs e)
{
    if (Request.FilePath == "/our-products.aspx")
    {
        Response.Redirect("/products.aspx", true);
    }
    if (Request.FilePath == "/about-us.aspx")
    {
        Response.RedirectPermanent("/about.aspx", true);
    }
}

VB.NET


Protected Sub Application_BeginRequest(ByVal sender As Object, _
   
ByVal e As EventArgs)
   
    If Request.FilePath = "/our-products.aspx" Then
        Response.Redirect("/products.aspx", True)
    End If
    If Request.FilePath = "/about-us.aspx" Then
        Response.RedirectPermanent("/about.aspx", True)
    End If
End Sub

Now let’s run our web application and make the following requests:

  • /our-products.aspx
  • /about-us.aspx

In both cases we will be redirected but redirections are different. Here is my little mix of FireBug outputs for these requests and I think it is very self describing.

Response.RedirectPermanent() has also overload with one parameter, just like Response.Redirect() does. If you have pages that exist in search engines but are moved to other location in your application then Response.RedirectPermanent() helps you build redirection controlling mechanism that likes to search engine spiders.


kick it on DotNetKicks.com vote it on Web Development Community pimp it Progg it Shout it
Posted: May 27 2009, 02:29 AM by DigiMortal | with 30 comment(s)
Filed under: ,
Visual Studio 2010: How to crash Windows 7

During Visual Studio 2010 testing I found interesting way how to crash Visual Studio 2010 so bad that my Windows 7 needs restart. Just follow these steps.

  1. Create new console application.
     
  2. Write there these two lines (first line sows that something is going on and second line keeps console window open):

    Console.WriteLine(“Press any key to exit …”);
    Console.ReadLine();
     
  3. Try to close console window by clicking on its close icon.

On my Windows 7 beta version Visual Studio 2010 hangs when I perform these steps. Console window stays opened and when I stop application then I experience horrible performance because csrss.exe hogs as much as CPU cycles as possible. My computer gets so slow that I heed to restart it. Closing Visual Studio 2010 doesn’t help.

If you want to output something and you are maniac window closer then use Debug.Write and Debug.WriteLine when you need to output something informal for you.


kick it on DotNetKicks.com pimp it Shout it
.Net Framework 4.0: Introducing BigInteger

My previous posting was about performance of Fibonacci numbers algorithms. In this posting I will introduce you some problems related to limits of our usual integers and introduce you new feature in .Net Framework 4.0 – big integers. Big integers are useful when solving different mathematical problems. Also they are used in cryptography.

As a first thing let’s see the problem we may face when we use our usual integers. Let’s use faster implementation of Fibonacci numbers algorithm so we don’t have to wait a long time to get results we need.

C#
public int Fibonacci(int x)
{
    var previousValue = -1;
    var currentResult = 1;
 
    for (var i = 0; i <= x; ++i)
    {
        var sum = currentResult + previousValue;
        previousValue = currentResult;
        currentResult = sum;
    }
 
    return currentResult;
}

VB.NET


Public Function Fibonacci(ByVal x As Integer) As Integer 
    Dim previousValue = -1 
    Dim currentResult = 1 
     
    For i = 0 To x 
        Dim sum = currentResult + previousValue 
        previousValue = currentResult 
        currentResult = sum 
    Next 
     
    Return currentResult 
End Function

Input Actual Expected
40 102334155 102334155
41 165580141 165580141
42 267914296 267914296
43 433494437 433494437
44 701408733 701408733
45 1134903170 1134903170
46 1836311903 1836311903
47 -1323752223 2971215073
48 512559680 4807526976
49 -811192543 7778742049
50 -298632863 12586269025

Now let’s take some value range where we can expect big numbers as result. Let’s take range from 40 to 50 and compare the results of our algorithm with expected results.

We can see that starting from 47 our results are different. 47 is the point where we go over integer limits and then we go to “next round” in integer scope. Same thing happens also with unsigned integer, long and unsigned long.

If we take some bigger input for our algorithm then we will get even larger numbers. 47 is small number and I am sure that scientific calculations use usually bigger inputs too and breaking over the limits of used type is almost sure.

You may also consider some other algorith that produces faster growth of results. Perfect candidate for this is factorial algorithm. By example 40! = 815915283247897734345611269596115894272000000000.

Introducing BigInteger class

.Net Framework 4.0 solves our problem. New namespace System.Numerics contains class called BigInteger. You can use objects based on this class as usual integers. This class also provides static methods for different mathematical operations on big integers. Let’s move now to BigInteger class with our Fibonacci numbers algorithm.

C#
public BigInteger Fibonacci(int x)
{
    var previousValue = new BigInteger(-1);
    var currentResult = new BigInteger(1);
 
    for (var i = 0; i <= x; ++i)
    {
        var sum = currentResult + previousValue;
        previousValue = currentResult;
        currentResult = sum;
    }
 
    return currentResult;
}

VB.NET


Public Function Fibonacci(ByVal x As Integer) As BigInteger
    Dim previousValue = New BigInteger(-1)
    Dim currentResult = New BigInteger(1)
    
    For i = 0 To x
        Dim sum = currentResult + previousValue
        previousValue = currentResult
        currentResult = sum
    Next
    
    Return currentResult
End Function

When we run this code we get expected results.

Some words about BigInteger structure

BigInteger is structure by its nature. It has bunch of static methods that let you perform different mathematical operations on BigIntegers. There are also many operators and type conversions defined for BigInteger so you can use BigIntegers like usual integers. Take look at the BigInteger members documentation.


kick it on DotNetKicks.com pimp it Progg it Shout it
Performance of Fibonacci numbers algorithms

Performance of algorithms is important topic if you want to write programs that work fast and doesn’t eat too much resources. In this example I will show you two implementations of famous Fibonacci numbers algorithm and let you compare how these two implementations perform. This posting will be also introduction to my next posting to keep it smaller and to keep focus on point.

You can read more about Fibonacci numbers from Data Structures and Algorithms with Object-Oriented Patterns in C#, chapter Example-Fibonacci Numbers.

Recursive implementation

Our first implementation of Fibonacci numbers uses recursive algorithm. Recursive algorithm is very short and also easy to read.

C#
public int FibonacciRecursive(int x)
{
    if (x == 0 || x == 1)
        return x;
 
    return FibonacciRecursive(x - 1) + 
           FibonacciRecursive(x - 2);
}

VB.NET


Public Function FibonacciRecursive(ByVal x As Integer) As Integer
    If x = 0 OrElse x = 1 Then
        Return x
    End If
    
    Return FibonacciRecursive(x - 1) + FibonacciRecursive(x - 2)
End Function

Experienced programmers should see here two dangers. First of them gets clear to others at the end of this posting. Second of them is simple: recursive code is harder to debug than flat code.

Flat implementation

The other implementation is not so short but it doesn’t call our algorithm again and again. It is also not so easy to read as first implementation.

C#
public int Fibonacci(int x)
{
    var previousValue = -1;
    var currentResult = 1;
 
    for (var i = 0; i <= x; ++i)
    {
        var sum = currentResult + previousValue;
        previousValue = currentResult;
        currentResult = sum;
    }
 
    return currentResult;
}

 
VB.NET
Public Function Fibonacci(ByVal x As Integer) As Integer
    Dim previousValue = -1
    Dim currentResult = 1
    
    For i = 0 To x
        Dim sum = currentResult + previousValue
        previousValue = currentResult
        currentResult = sum
    Next
    
    Return currentResult
End Function

Before I say anything else let’s compare performance of those implementations.

Performance

Now let’s see how these implementations perform. I am sure that less experienced programmers will check if these implementations give same results and they will try them with pretty small inputs. But… look at the results.


Performance results of recursive and flat implementations of
Fibonacci numbers algorithm.

Horizontal axis shows input integers. Vertical axis shows us time in seconds that calculation took. For smaller inputs both implementations perform very well. Near 30 performance of recursive implementations starts going worse. For the time of last input (that is 41) we are sure that recursive implementation is a highway to hell. But performance of flat implementation is still okay.

This example is good illustration why we must test all the implementations we have before making decision which implementation to use.

Update: Bart Czernicki asked in his comment about F# performance when using recursive calls. I tried it out and F# performs very well in this scenario. In F# you can use recursive calls without any problems as my tests showed me.


kick it on DotNetKicks.com pimp it Shout it
SharePoint: SPList.Clear() extension method

Currently there is no good method in SharePoint for deleting all items from list. But there are solutions that need this kind of functionality. During one of my projects I wrote extension method for SPList that removes all items from it.

C#
public static void Clear(this SPList list)
{
    var count = list.ItemCount;
 
    for (var i = count - 1; i >= 0; i--)
    {
        var item = list.GetItemById(i);
        item.Delete();
    }
 
    list.Update();
}

VB.NET


<System.Runtime.CompilerServices.Extension> _
Public Shared Sub Clear(ByVal list As SPList)
    Dim count = list.ItemCount
    
    For i = count - 1 To 0 Step -1
        Dim item = list.GetItemById(i)
        item.Delete()
    Next
    
    list.Update()
End Sub

Feel free to use this code. Also let me know if I can make this code better somehow.

Posted: May 22 2009, 02:46 PM by DigiMortal | with 16 comment(s)
Filed under:
.Net Framework 4.0: System.Linq.Parallel

.Net Framework 4.0 has parallel computing extensions for LINQ. Previously it was possible to download parallel extensions for LINQ separately from CodePlex. Of course, you can still use these extensions if you have older version that 4.0. I wrote a little, simple and pretty pointless example that illustrates how parallel queries work in .Net Framework 4.0.

My example creates simple data source that contains integers from 1 to 100. Then it queries this source two times. At first we will run query with parallel extensions and then we will run usual LINQ query. After querying we will write out the results. So it is really simple code but it returns some interesting results.

C#
private static void ParallelAndSerialQueries()
{
    // Source data that parallel and serial queries use.
    var source = Enumerable.Range(1, 100);
 
    // Perform parallel query
    var parallelQuery = from p in source.AsParallel()
                        where p.ToString().Contains("1")
                        select p;
 
    parallelQuery.ForAll((x) =>
    {
        Console.WriteLine("Parallel: " + x);
    });
 
    // Perform serial query
    var serialQuery = from s in source
                      where s.ToString().Contains("1")
                      select s;
    serialQuery.All((x) =>
    {
        Console.WriteLine("Serial: " + x);
        return true;
    });
 
    Console.WriteLine("Press any key to exit...");
    Console.ReadLine();
}

 
VB.NET
Private Shared Sub ParallelPerformance()
    ' Source data that parallel and serial queries use.
    Dim source = Enumerable.Range(1, 100)
    
    ' Perform parallel query
    Dim parallelQuery = From p In source.AsParallel() _
        Where p.ToString().Contains("1") _
        Select p
    
    parallelQuery.ForAll(Function(x) Do
        Console.WriteLine("Parallel: " & x)
    End Function)
    
    ' Perform serial query
    Dim serialQuery = From s In source _
        Where s.ToString().Contains("1") _
        Select s

    serialQuery.All(Function(x) Do
        Console.WriteLine("Serial: " & x)
        Return True
    End Function)
    
    Console.WriteLine("Press any key to exit...")
    Console.ReadLine()
End Sub

Serial Parallel

1
10
11
12
13
14
15
16
17
18
19
21
31
41
51
61
71
81
91
100

10
11
1
14
12
13
16
17
18
19
21
31
15
51
61
41
71
81
100
91

Now let’s compare data that queries returned. We can see that in the case of classic serial LINQ query and data processing all the values are handled as they were sorted. Bigger number is always after smaller number. This is the same order as numbers have in our data source.

Parallel results are different. If we look at the results we can see that numbers are not ordered all the time. Some numbers are printed out much sooner or later than we may be expected before. This is because of the parallel nature of first query.

Parallel activities doesn’t run on same processor core. Some cores have more things to do and some cores have more free resources. That’s why parallel results have seemingly random order. Okay, their order is not random and as I just said it depends on workload of cores.

Is parallel processing more powerful?

Parallel computing is not another silver bullet that automagically solves performance issues. In the current example serial query was about two times faster that parallel one (exact numbers with 10000 elements in source: serial – 0.68 seconds, parallel – 1.31 seconds). Of course there are scenarios when parallel computing performs way better than serial computing. I recommend you to test the performance of your LINQ queries before you make your final decision over serial and parallel processing.


kick it on DotNetKicks.com pimp it Progg it Shout it
More Posts Next page »