<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Luis Guerrero EN &#187; .NET</title>
	<atom:link href="http://luisguerrero.net/en/category/net/feed/" rel="self" type="application/rss+xml" />
	<link>http://luisguerrero.net/en</link>
	<description>.NET Stuff from London, Windows Phone 7, Silverlight, WPF and debugging</description>
	<lastBuildDate>Sat, 30 Apr 2011 15:44:21 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Run elevated task at any point of the Azure Rol lifetime.</title>
		<link>http://luisguerrero.net/en/2011/04/30/run-elevated-task-at-any-point-of-the-azure-rol-lifetime/</link>
		<comments>http://luisguerrero.net/en/2011/04/30/run-elevated-task-at-any-point-of-the-azure-rol-lifetime/#comments</comments>
		<pubDate>Sat, 30 Apr 2011 15:36:30 +0000</pubDate>
		<dc:creator>Guerrerotook</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Azure]]></category>
		<category><![CDATA[wcf]]></category>
		<category><![CDATA[elevated]]></category>
		<category><![CDATA[role]]></category>
		<category><![CDATA[startup]]></category>
		<category><![CDATA[task]]></category>

		<guid isPermaLink="false">http://luisguerrero.net/en/?p=40</guid>
		<description><![CDATA[There are two mostly common used for Windows Azure, starting a new 100% .NET project on Windows Azure, or migrate a legacy project to the cloud. Talking from this point legacy project could be the most difficult project of all, because can use COM components during him lifetime. As you may know all the Windows [...]]]></description>
			<content:encoded><![CDATA[<p>There are two mostly common used for Windows Azure, starting a new 100% .NET project on Windows Azure, or migrate a legacy project to the cloud. Talking from this point legacy project could be the most difficult project of all, because can use COM components during him lifetime. As you may know all the Windows Azure roles are clean machine so it’s means that you need to install manually all your component COM. Normally this issue is solved by placing on the startup node of the Role configuration file, a .cmd file with all the registration of the COM components.</p>
<p>But what happens if during role’s lifetime you need to execute a task elevated? You can’t do that because the hosting process of the worker role and web role is not executing with elevated rights. So we have to find a place where we can execute task with elevated rights, and this places is the roll’s startup node. So what we have to do is have a sentinel program up and running at roll’s startup and make this sentinel program to accept requests to execute process.</p>
<p>So this is exactly what we are going to do, using WCF to open a Windows pipe to enable communication between two different process in the same machine, enabling the process to send message with the necessary information to run this elevated task.</p>
<p>Let’s do it!</p>
<h1>Service definition.</h1>
<p>Since all we need is a WCF service be exposed on NetNamedPipeBinding, first of all we have to define a service contract with the operation contract we need. In this case we only need one operation, ExecuteTask.</p>
<div style="border-bottom: gray 1px solid; border-left: gray 1px solid; padding-bottom: 4px; line-height: 12pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; max-height: 200px; font-size: 8pt; overflow: auto; border-top: gray 1px solid; cursor: text; border-right: gray 1px solid; padding-top: 4px">
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px">[ServiceContract(Namespace = <span style="color: #006080">&quot;http://azure.plainconcepts.com/schemas/04/2011/azure/executionhost&quot;</span>)]
<span style="color: #0000ff">public</span> <span style="color: #0000ff">interface</span> IExecutionHost
{
    [OperationContract]
    <span style="color: #0000ff">void</span> ExecuteTask(ProcessTask host);
}</pre>
</div>
<p>Once we define the service contract now is the time to create the service itself, who is responsible to finally execute the tasks. </p>
<div style="border-bottom: gray 1px solid; border-left: gray 1px solid; padding-bottom: 4px; line-height: 12pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; max-height: 200px; font-size: 8pt; overflow: auto; border-top: gray 1px solid; cursor: text; border-right: gray 1px solid; padding-top: 4px">
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px">[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
<span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> ExecutionHostService : IExecutionHost
{
    <span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> ExecuteTask(ProcessTask host)
    {
        Process process = <span style="color: #0000ff">new</span> Process();
        process.StartInfo = host.StartInfo;
        process.Start();
    }
}</pre>
</div>
<p>When we have done this, the next step is host the server itself on the sentinel process that will handle the requests, as we said before we’re going to use the NetNamedPipeBinding.</p>
<div style="border-bottom: gray 1px solid; border-left: gray 1px solid; padding-bottom: 4px; line-height: 12pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; max-height: 200px; font-size: 8pt; overflow: auto; border-top: gray 1px solid; cursor: text; border-right: gray 1px solid; padding-top: 4px">
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> ExecutionHostServiceManager
{
    <span style="color: #0000ff">public</span> ExecutionHostServiceManager()
    {
        service = <span style="color: #0000ff">new</span> ExecutionHostService();
        ServiceHost host = <span style="color: #0000ff">new</span> ServiceHost(service);

        <span style="color: #0000ff">string</span> address = <span style="color: #006080">&quot;net.pipe://PlainConcepts/Azure/ExecutionHost&quot;</span>;
        NetNamedPipeBinding binding = <span style="color: #0000ff">new</span> NetNamedPipeBinding(NetNamedPipeSecurityMode.None);
        host.AddServiceEndpoint(<span style="color: #0000ff">typeof</span>(IExecutionHost), binding, address);

        <span style="color: #008000">// Add a mex endpoint</span>
        <span style="color: #0000ff">long</span> maxBufferPoolSize = binding.MaxBufferPoolSize;

        <span style="color: #0000ff">int</span> maxBufferSize = binding.MaxBufferSize;

        <span style="color: #0000ff">int</span> maxConnections = binding.MaxConnections;

        <span style="color: #0000ff">long</span> maxReceivedMessageSize =
            binding.MaxReceivedMessageSize;

        NetNamedPipeSecurity security = binding.Security;

        <span style="color: #0000ff">string</span> scheme = binding.Scheme;

        XmlDictionaryReaderQuotas readerQuotas =
            binding.ReaderQuotas;

        BindingElementCollection bCollection = binding.CreateBindingElements();

        HostNameComparisonMode hostNameComparisonMode =
            binding.HostNameComparisonMode;

        <span style="color: #0000ff">bool</span> TransactionFlow = binding.TransactionFlow;

        TransactionProtocol transactionProtocol =
            binding.TransactionProtocol;

        EnvelopeVersion envelopeVersion =
            binding.EnvelopeVersion;

        TransferMode transferMode =
            binding.TransferMode;
        host.Open();
    }

    <span style="color: #0000ff">private</span> ExecutionHostService service;
}</pre>
</div>
<p>And that is!</p>
<p>Now we have to put this together in a console application and wait forever.</p>
<div style="border-bottom: gray 1px solid; border-left: gray 1px solid; padding-bottom: 4px; line-height: 12pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; max-height: 200px; font-size: 8pt; overflow: auto; border-top: gray 1px solid; cursor: text; border-right: gray 1px solid; padding-top: 4px">
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #0000ff">class</span> Program
{
    <span style="color: #0000ff">static</span> <span style="color: #0000ff">void</span> Main(<span style="color: #0000ff">string</span>[] args)
    {
        <span style="color: #0000ff">new</span> ExecutionHostServiceManager();
        Thread.Sleep(Timeout.Infinite);
    }
}</pre>
</div>
<h3>Making call to the service</h3>
<p>We now have the service contract, the service definition and the hosting process, now it’s time to define the client and make call to the servicer. Since we’re using WCF we need to define a class that will handle the request to the pipe. To accomplish this it’s necessary to inherit from ClientBase&lt;T&gt;, and T need to the service contract of the service.</p>
<div style="border-bottom: gray 1px solid; border-left: gray 1px solid; padding-bottom: 4px; line-height: 12pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; max-height: 200px; font-size: 8pt; overflow: auto; border-top: gray 1px solid; cursor: text; border-right: gray 1px solid; padding-top: 4px">
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> ExecutionHostClient : ClientBase&lt;IExecutionHost&gt;
{
    <span style="color: #0000ff">static</span> ExecutionHostClient()
    {
        <span style="color: #0000ff">string</span> address = <span style="color: #006080">&quot;net.pipe://PlainConcepts/Azure/ExecutionHost&quot;</span>;
        NetNamedPipeBinding binding = <span style="color: #0000ff">new</span> NetNamedPipeBinding(NetNamedPipeSecurityMode.None);
        binding.CloseTimeout = TimeSpan.MaxValue;
        binding.ReceiveTimeout = TimeSpan.MaxValue;
        binding.SendTimeout = TimeSpan.MaxValue;
        EndpointAddress endpoint = <span style="color: #0000ff">new</span> EndpointAddress(address);
        client = <span style="color: #0000ff">new</span> ExecutionHostClient(binding, endpoint);
    }

    <span style="color: #0000ff">public</span> ExecutionHostClient(Binding binding, EndpointAddress remoteAddress) :
        <span style="color: #0000ff">base</span>(binding, remoteAddress)
    {
    }

    <span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> ExecuteTask(ProcessTask task)
    {
        Channel.ExecuteTask(task);
    }

    <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">void</span> ExecuteRemoteTask(ProcessTask task)
    {
        client.ExecuteTask(task);
    }

    <span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> ExecutionHostClient client;
}</pre>
</div>
<p>It’s important to create this proxy with the same configuration of the server, because we’re not using the default Visual Studio code generated proxy, and it’s our responsibility to create the binding and the address of the endpoint.</p>
<h3>Invoking services</h3>
<p>In this example we are registering COM components by calling the regsvc32.exe in code. We looking for dll files on a known folder of our Windows Azure Solution and invoke the service to make the elevated call.</p>
<div style="border-bottom: gray 1px solid; border-left: gray 1px solid; padding-bottom: 4px; line-height: 12pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; max-height: 200px; font-size: 8pt; overflow: auto; border-top: gray 1px solid; cursor: text; border-right: gray 1px solid; padding-top: 4px">
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px"><span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> RegisterComHelper
{
    <span style="color: #0000ff">public</span> RegisterComHelper()
    {

    }

    <span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> Register()
    {
        <span style="color: #008000">// hay que buscar la localizacion en el servidor de azure de donde estan los ensamblados</span>
        <span style="color: #008000">// como no sabemos donde estan los ficheros tenemos que buscar el modulo </span>
        <span style="color: #008000">// Habitania.RegisterCom.dll que es especifico para este ejemplo</span>
        <span style="color: #008000">// así nos aseguramos que estamos buscando la dll correcta</span>
        Process current = Process.GetCurrentProcess();
        var found = (from p <span style="color: #0000ff">in</span> current.Modules.Cast&lt;ProcessModule&gt;().ToList()
                     <span style="color: #0000ff">where</span> p.ModuleName == <span style="color: #006080">&quot;PlainConcepts.Azure.WorkerRoleDemo.dll&quot;</span>
                     select p).FirstOrDefault();

        <span style="color: #0000ff">if</span> (found != <span style="color: #0000ff">null</span>)
        {
            <span style="color: #008000">// a partir de la locacion del modulo cargada por el proceso </span>
            <span style="color: #008000">// somos capaces de encontrar la informacion del directorio y buscar</span>
            <span style="color: #008000">// la carpeta dlls que contiene la lista de dlls que queremos registar</span>
            <span style="color: #0000ff">string</span> directoryLocation = Path.GetDirectoryName(found.FileName);

            <span style="color: #0000ff">string</span> dllPath = Path.Combine(directoryLocation, <span style="color: #006080">&quot;V3COM30&quot;</span>);

            <span style="color: #0000ff">string</span>[] files = Directory.GetFiles(dllPath);

            <span style="color: #0000ff">foreach</span> (var item <span style="color: #0000ff">in</span> files)
            {
                <span style="color: #0000ff">if</span> (item.EndsWith(<span style="color: #006080">&quot;.dll&quot;</span>))
                    RegisterComObject(item);
            }

            dllPath = Path.Combine(directoryLocation, <span style="color: #006080">&quot;V3COM&quot;</span>);

            files = Directory.GetFiles(dllPath);

            <span style="color: #0000ff">foreach</span> (var item <span style="color: #0000ff">in</span> files)
            {
                <span style="color: #0000ff">if</span> (item.EndsWith(<span style="color: #006080">&quot;.dll&quot;</span>))
                    RegisterComObject(item);
            }
        }
    }

    <span style="color: #0000ff">private</span> <span style="color: #0000ff">void</span> RegisterComObject(<span style="color: #0000ff">string</span> filePath)
    {
        ProcessStartInfo info = <span style="color: #0000ff">new</span> ProcessStartInfo();
        info.FileName = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.System),
            <span style="color: #006080">&quot;regsvr32.exe&quot;</span>);
        info.Arguments = <span style="color: #0000ff">string</span>.Format(<span style="color: #006080">&quot;/i {0}&quot;</span>, filePath);
        info.UseShellExecute = <span style="color: #0000ff">false</span>;

        ExecutionHostClient.ExecuteRemoteTask(<span style="color: #0000ff">new</span> ProcessTask()
        {
            StartInfo = info
        });
    }
}</pre>
</div>
<p>This way of invoking task on Windows Azure seems a little bit complicated, but once is done can be super flexible and permit to extend this demo with custom task and background tasks.</p>
<p>The complete source code can be downloaded from <a href="http://www.luisguerrero.net/downloads/ExecuteProcessElevated.zip">here</a>.</p>
<p>Luis Guererro.</p>
]]></content:encoded>
			<wfw:commentRss>http://luisguerrero.net/en/2011/04/30/run-elevated-task-at-any-point-of-the-azure-rol-lifetime/feed/</wfw:commentRss>
		<slash:comments>1689</slash:comments>
		</item>
		<item>
		<title>Concurrent programming and Managed Extensibilty Framework</title>
		<link>http://luisguerrero.net/en/2010/03/04/concurrent-programming-and-managed-extensibilty-framework/</link>
		<comments>http://luisguerrero.net/en/2010/03/04/concurrent-programming-and-managed-extensibilty-framework/#comments</comments>
		<pubDate>Thu, 04 Mar 2010 15:52:43 +0000</pubDate>
		<dc:creator>Guerrerotook</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Concurrent]]></category>
		<category><![CDATA[MEF]]></category>

		<guid isPermaLink="false">http://www.luisguerrero.net/en/post.aspx?id=536a3435-37ec-4a7b-ad08-6fbbc9f886e5</guid>
		<description><![CDATA[Here they are! Last month I have been talking about concurrent programming on .NET Framework with Task Parallel Library and MEF (Managed Extensibility Framework), so here you have all the resources, the presentation in PowerPoint format and some demos. Task Parallel Lirarty demos in Visual Studio 2010 RC format There are no demos from MEF [...]]]></description>
			<content:encoded><![CDATA[<p>Here they are! Last month I have been talking about concurrent programming on .NET Framework with Task Parallel Library and MEF (Managed Extensibility Framework), so here you have all the resources, the presentation in PowerPoint format and some demos.</p>
<p style="text-align: center;"><a title="Concurrent programming and MEF" href="http://www.luisguerrero.net/downloads/Concurrent programming and MEF.pptx"><img class="aligncenter" style="margin-left: auto; margin-right: auto; border: 0px initial initial;" src="http://www.luisguerrero.net/Images/f929e70d1b50_EEB8/image_thumb.png" border="0" alt="clip_image001" /></a></p>
<p><a title="ParallelDemos" href="http://www.luisguerrero.net/downloads/ParallelDemos.zip" target="_blank">Task Parallel Lirarty demos in Visual Studio 2010 RC format</a></p>
<p>There are no demos from MEF but you can download some from <a href="http://www.codeplex.com/mef/">http://www.codeplex.com/mef/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://luisguerrero.net/en/2010/03/04/concurrent-programming-and-managed-extensibilty-framework/feed/</wfw:commentRss>
		<slash:comments>1881</slash:comments>
		</item>
		<item>
		<title>Writing high performance parallel code with monitors</title>
		<link>http://luisguerrero.net/en/2009/11/29/writing-high-performance-parallel-code-with-monitors/</link>
		<comments>http://luisguerrero.net/en/2009/11/29/writing-high-performance-parallel-code-with-monitors/#comments</comments>
		<pubDate>Sun, 29 Nov 2009 23:02:09 +0000</pubDate>
		<dc:creator>Guerrerotook</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Concurrent]]></category>

		<guid isPermaLink="false">http://www.luisguerrero.net/en/post.aspx?id=c8e10a96-8a2c-4758-9c1d-35faf7e39bf1</guid>
		<description><![CDATA[Multithread application is going to be next issue for developer, and we need to be ready for this big change. In .NET Framework 4, Microsoft introduced Task Parallel Library, a set of API that helps developer creating concurrent applications. That’s means that you don’t have to take care about all those concurrent issues anymore, its [...]]]></description>
			<content:encoded><![CDATA[<p>Multithread application is going to be next issue for developer, and we need to be ready for this big change. In .NET Framework 4, Microsoft introduced Task Parallel Library, a set of API that helps developer creating concurrent applications. That’s means that you don’t have to take care about all those concurrent issues anymore, its mean now is easier to create concurrent code. </p>
<p>Currently I’m working in an application that makes a hard use of all TLP code. What I do is creating a lot of <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.task(VS.100).aspx" target="_blank">Task</a> objects to manage the executing of a set of rules that have to be executed for each Uri. I maintain a list with all the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.task(VS.100).aspx" target="_blank">Task</a> object to observer during time, how much <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.task(VS.100).aspx" target="_blank">Task</a> are now running, and make some statistics about software speed. </p>
<p>This means I have UI, created in WPF that need to communicate with this code to get all running <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.task(VS.100).aspx" target="_blank">Task</a> and display this information in the UI. Since I’m using a simple <a href="http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx" target="_blank">List&lt;Task&gt;</a> to get a reference to all task created during my application execution, I need a way to lock and add Tasks to this list, enumerate this list and remove Tasks. But I want this lock to be shortest one and only lock to important operations like add and remove items when Task are finished.</p>
<p>So I have two important operations, create new Task and add to this list, and when the Task is finish removes this <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.task(VS.100).aspx" target="_blank">Task</a> from the list, and for that I need to wait if the lock is acquired by other thread, because multiple Tasks can finish at the same time.</p>
<p>Creating task is done by a timer inside my application and this timer is set to run each second to check if the running Task in the system are lower that minimum Task running. If this is true is the moment create more Task and add to the list. Since this timer is executed every second I’ll need to lock my list of <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.task(VS.100).aspx" target="_blank">Task</a>, do my work and then release the lock. I’m using the list as lock object. But this timer can wait more than one second until the lock is released, because other Task are now executing and finish work and remove items from my list, so It’s mean I’m creating a classic convoy in my application. Every time my timer method is executed and wait until the lock to release, this time is bigger that timer elapsed time, so I need a way to wait only a certain period of time.</p>
<p>What I do in this method is using the new API for <a href="http://msdn.microsoft.com/en-us/library/dd270976(VS.100).aspx" target="_blank">Monitor</a> in .NET 4 that attempts, for a number of milliseconds, to acquire an exclusive lock and atomically set a value that indicates whether the lock was taken or not. In my case I set these milliseconds in 400, because in this method I do more stuff than work with my list of Task. If the lock is bigger than 400ms the lock will not be acquired.</p>
<div style="border-bottom: gray 1px solid; border-left: gray 1px solid; padding-bottom: 4px; line-height: 12pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: consolas, 'Courier New', courier, monospace; max-height: 200px; font-size: 8pt; overflow: auto; border-top: gray 1px solid; cursor: text; border-right: gray 1px solid; padding-top: 4px">
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, 'Courier New', courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #0000ff">bool</span> taken = <span style="color: #0000ff">false</span>;
<span style="color: #0000ff">try</span>
{
    Monitor.TryEnter(task, 400, <span style="color: #0000ff">ref</span> taken);
    <span style="color: #0000ff">if</span> (taken)
    {
        <span style="color: #0000ff">if</span> (!cancelationTokenSource.IsCancellationRequested)
        {
            var count = (from p <span style="color: #0000ff">in</span> task
                         <span style="color: #0000ff">where</span> p.Status == TaskStatus.Running || p.Status == TaskStatus.WaitingToRun
                         select p).Count();
        }
    }
}
<span style="color: #0000ff">finally</span>
{
    <span style="color: #0000ff">if</span> (taken)
    {
        Monitor.Exit(task);
    }
}</pre>
</div>
<p>As you can see in this code I’m calling <a href="http://msdn.microsoft.com/en-us/library/dd270976(VS.100).aspx" target="_blank">Monitor.TryEnter</a> inside a try/catch block, and then in the finally block if the lock was acquired I release the lock by calling <a href="http://msdn.microsoft.com/en-us/library/system.threading.monitor.exit(VS.100).aspx" target="_blank">Monitor.Exit</a>. I do in that way because if during the execution of my code an exception is throw, the call to <a href="http://msdn.microsoft.com/en-us/library/system.threading.monitor.exit(VS.100).aspx" target="_blank">Monitor.Exit</a> at the end of the code will not be executed anymore, causing that I have a lock that will never be released. </p>
<p>My other scenario is when I want to get all Task to count how much task are now running, I do the same inside get accessor of the property Task, but in this case I only wait for 250ms instead of 400ms. If the lock is acquired I copy the collection into a new list and there I can safety count how much Task are running.</p>
<div style="border-bottom: gray 1px solid; border-left: gray 1px solid; padding-bottom: 4px; line-height: 12pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: consolas, 'Courier New', courier, monospace; max-height: 200px; font-size: 8pt; overflow: auto; border-top: gray 1px solid; cursor: text; border-right: gray 1px solid; padding-top: 4px">
<pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, 'Courier New', courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #0000ff">public</span> List&lt;Task&gt; Tasks
{
    get
    {
        <span style="color: #0000ff">bool</span> taken = <span style="color: #0000ff">false</span>;
        List&lt;Task&gt; list = <span style="color: #0000ff">null</span>;
        <span style="color: #0000ff">try</span>
        {
            Monitor.TryEnter(task, 250, <span style="color: #0000ff">ref</span> taken);
            <span style="color: #0000ff">if</span> (taken)
            {
                list = <span style="color: #0000ff">new</span> List&lt;Task&gt;(task.ToArray());
            }
        }
        <span style="color: #0000ff">finally</span>
        {
            <span style="color: #0000ff">if</span> (taken)
            {
                Monitor.Exit(task);
            }
        }
        <span style="color: #0000ff">return</span> list;
    }
}</pre>
</div>
<p>This solution is simple and keeps your code with the lowest contention rate giving boots to those important operations that need to wait until the lock is released. </p>
<p>I could also create a wrap over List&lt;T&gt; list using <a href="http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx" target="_blank">ReaderWriterLockSlim</a> to control read and write operation during lock, but <a href="http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx" target="_blank">ReaderWriterLockSlim</a> is focus on multiple readers and only one writer, and I my application I have multiple writers and only one reader. </p>
<p>All the best.</p>
<p>Luis.</p>
]]></content:encoded>
			<wfw:commentRss>http://luisguerrero.net/en/2009/11/29/writing-high-performance-parallel-code-with-monitors/feed/</wfw:commentRss>
		<slash:comments>2371</slash:comments>
		</item>
	</channel>
</rss>

