A look at CSharp Volatile Keyword

The other day the keyword Volatile came up in a discussion and I did not know the use of it.  So I figured, why not, let’s dig into it.

The volatile keyword can be put onto a field that may be accessed my multiple threads at the same time.  The effect of applying the fields with volatile is neat.  The compiler makes numerous optimizations and for fields reordering optimizations can take place.  When you apply the volatile keyword to the field declaration, compiler optimizations will not be applied to that field.

Take a look at the example below on declaring a public variable as volatile.

 private volatile bool _Stop;

Now let’s take that and put it into an application.  [more] The following example is based off of MSDN’s example.

public class WorkerClass
{
    // Called when a thread starts
    public void Working()
    {
        while (!_Stop)
        {
            Console.WriteLine("Worker thread: working...");
        }
        Console.WriteLine("Worker thread: terminating gracefully.");
    }

    public void RequestStop()
    {
        _Stop = true;
    }

    // Keyword volatile is used as a hint to the compiler that this data
    // member is accessed by multiple threads.
    private volatile bool _Stop;
}

public class WorkerThreadExample
{
    static void Main()
    {
        // Create the worker thread object.
        WorkerClass workerObject = new WorkerClass();
        Thread workerThread = new Thread(workerObject.Working);

        // Start the worker thread.
        workerThread.Start();
        Console.WriteLine("Main thread: starting worker thread...");

        // Loop until the worker thread activates.
        while (!workerThread.IsAlive)
        {
        }

        // Put the main thread to sleep for 1 millisecond to
        // allow the worker thread to do some work.
        Thread.Sleep(1);

        // Request that the worker thread stop itself.
        workerObject.RequestStop();

        // Use the Thread.Join method to block the current thread 
        // until the object's thread terminates.
        workerThread.Join();
        Console.WriteLine("Main thread: worker thread has terminated.");

        Console.ReadLine();
    }
    // Sample output:
    // Main thread: starting worker thread...
    // Worker thread: working...
    // Worker thread: working...
    // Worker thread: working...
    // Worker thread: working...
    // Worker thread: working...
    // Worker thread: working...
    // Worker thread: terminating gracefully.
    // Main thread: worker thread has terminated.
}

A lot of the explaining is done through the comments so I will save the reiteration of what has already been written.  Multithreading can cause some serious problems when they are executing at the same time.  By using the volatile keyword, it’s not causing synchronization of any parts, it’s instead telling the compiler to leave this field alone and not change the order of it.

Here is another example usage that may be a little easier on the eyes.

using System;
using System.Threading;
class Test
{
   public static int result;   
   public static volatile bool finished;
   static void Thread2() {
      result = 143;    
      finished = true; 
   }
   static void Main() {
      finished = false;
      // Run Thread2() in a new thread
      new Thread(new ThreadStart(Thread2)).Start();
      // Wait for Thread2 to signal that it has a result by setting
      // finished to true.
      for (;;) {
         if (finished) {
            Console.WriteLine("result = {0}", result);
            return;
         }
      }
   }
}

The main point to take from the second example is that with the finished variable set to volatile, it makes it impermissible for the store to result to be visible to the main thread before the store to finish.  If volatile is not used, it would be permissible for the main thread to see finished sooner and possible read the value of 0 from result.  Using volatile will ensure that this sort of ordering issues will not occur.  This does not take the place of the lock statement; it solely restricts some of the optimizations implemented by the compiler.


For Loop Using UInt16 MaxValue

A demonstration of a For Loop Using UInt16 MaxValue. How would you iterate through all of the values in an unsigned 16-bit integer?

The following two loops will not work:


for (UInt16 i = 0; i < UInt16.MaxValue; i++)
{
    // Do something
}

for (UInt16 i = 0; i <= UInt16.MaxValue; i++)
{
    // Do something
}

The first loop skips the last value; the second loop goes into an infinite loop when it rolls over.

Let’s take a look at the first loop.


for (UInt16 i = 0; i < UInt16.MaxValue; i++)
{
    // Do something
}

First we need to know what UInt16.MaxValue equates to as a value.  UInt16.MaxValue is hexadecimal 0xFFFF which is a constant value of 65535.  So when we are looking into the loop with for (UInt16 i = 0; i < UInt16.MaxValue; i++) the last iteration will not happen because we would need an overflow value of 65536.  However, since UInt16.MaxValue is a constant value of 65535, the last value causes the loop to exit before the last Do Something is completed.

Let’s take a look at the second loop.

for (UInt16 i = 0; i <= UInt16.MaxValue; i++)
{
    // Do something
}

The problem we are seeing here is an infinite loop gets created.  This again takes us to needing to understand how UInt16.MaxValue works.  As we said, UInt16.MaxValue is the hexadecimal value of 0xFFFF.  So if you look at this loop if will actually go through and complete the last iteration at 65535.  However, in terms of this hexadecimal value, when you add 1 to it after the last iteration if wraps around to 0 again. Hence, our infinite loop problem.

Solution? Use a do/while loop.

ushort i = 0;
do
{
    // do something
}
 while(i++ < UInt16.MaxValue);

This is close to the first loop in our question, but it will cause the Do Something to iterate all the way through before it does a check on the UInt16 value.

Here it is as a test console app to confirm all the above from Guy Ellis.


static void Main(string[] args){
    UInt16 i = 0;
    do    {        if (i == UInt16.MinValue)
        {
            Console.WriteLine("MinValue");
        }
        if (i == UInt16.MaxValue)
        {
            Console.WriteLine("MaxValue");
        }
    } while (i++ < UInt16.MaxValue);
    Console.WriteLine("Enter to finish...");
    Console.ReadLine();}


Multithreading with Parameters

I ran into a task the other day to make my service calls run asynchronously for performance reasons and solved this by Multithreading with Parameters.  When the front of site gets pounded, the logging service will be making too many inline calls causing performance problems. So I had to do some minor tweaking which really was only implementing to new methods.

So basically we had a call right into our service.

_service.LogServiceCall(string log, string info, long number);

First change we make is call a new method to spin off new threads and we will need to create a new object to store the parameters in.

_service.LogServiceCallInParallel(string log, string info, long number); //New Method Call

public class LogginParams
{
    public string Log { get; set; }
    public string Info { get; set; }
    public long Number { get; set; }
}

When creating a thread with parameters you have to pass in an object with parameters. So we will create LoggingParams object, start the thread, then split the parameters back out.  Let’s take a look at the thread starting.

public void LogServiceCallInParallel (string log, string info, long number)
{
    //Create object
    LogginParams logParams = new LogginParams
    {
        Log = log,
        Info = info,
        Number = number
    };

    //Create new thread.
    Thread logThread = new Thread(LogServiceCall);

    //Start new thread
    logThread.Start(logParams);
}

Now all we have to do is call an overloaded method of our original method so that it will work as designed just now with multithreading.

private void LogServiceCall(object parameterObject)
{
    LogginParams pLoggingParams = (LogginParams)parameterObject;
    LogServiceCall(pLoggingParams.Log, pLoggingParams.Info, pLoggingParams.Number);
}

So as you can see here, all we are doing is breaking back out the object and then calling our original method that was being used.


WCF Binding Configuration with a Certificate

I recently had my first encounter with setting up a WCF service and had to set up WCF Binding Configuration with a Certificate to an already configured end point.  So mainly for my knowledge I thought it would be a good idea to document some notable pieces while it’s fresh in my mind.  Setting up the binding and endpoint configurations with using a certificate took a little bit of trial and error but is not too bad to understand.

The configuration for the WCF service goes in the web.config.  The first part we will look at is the <endpoint>.

Here is a sample endpoint.

<endpoint address="http://localhost:8001/Service/service.svc"
      binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IService1"
      contract=" ServiceIntegration.IService1" name="ServiceIntegration"
      behaviorConfiguration="CustomBehavior" />

Each endpoint consists of four main properties:

  • An address that indicates where the endpoint can be found.
  • A binding that specifies how a client can communicate with the endpoint.
  • A contract that identifies the operations available.
  • A set of behaviors that specify local implementation details of the endpoint.

The next part of the configuration is the binding attribute.  This will correspond to the WSHttpBinding_IService1 above denoting that it will use this specific binding.

<bindings>
  <wsHttpBinding>
    <binding name="WSHttpBinding_IService1" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
      <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
      <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" />
      <security mode="Transport">
        <transport clientCredentialType="Certificate" />
        <message clientCredentialType="None" />
      </security>
    </binding>
  </wsHttpBinding>
</bindings>

This properties within are pretty straight forward.  The part I want to bring your attention to is the <security> properties.  Since we have to use our installed certificate as our accessor into the endpoint we have to define how to send and what to send.  Here we pick transport designating that security is being provided by using a secure transport (example, HTTPS).

Finally, we are going to create our CustomBehavior.  It is important here to input the exact name of your certificate so the services knows what certificate to use.

<behaviors>
  <endpointBehaviors>
    <behavior name=" CustomBehavior ">
      <clientCredentials>
        <clientCertificate findValue="certificate.not.real.com" x509FindType="FindBySubjectName" />
      </clientCredentials>
    </behavior>
  </endpointBehaviors>
</behaviors>

There are many other properties and values that can be used but I found that this method worked for my purpose.  If you have a better way or a different way of going about this I would love to hear it.

String versus StringBuilder

String versus StringBuilder and what some of the pros and cons are to each. To start off we need to understand what immutable means and what mutable means.  Immutable in basic terms means the original object cannot be altered.  An attempt to alter or concatenate to an existing object will result in a new object being created each time.  A mutable object means that you can add to the existing object without a new one being created.

A String is an immutable object.  So every time that we change a string, a new string is actually getting created.  This is not the most efficient use of memory if you are doing multiple concatenations to a string, you will be creating a new string object each time. This whole discussion of immutability is a deep subject for another post.

So let’s take a look at this loop for if you have a 100,000 iterations of adding a sentence to a string. This is just adding a sentence to the string each time, however because its an immutable object it is creating a new string object each time.  This has memory efficiency issues as well as it can slow down performance when you get large strings and many iterations of adding them together.

private static string LoopResult(string result)
{
    for (int i = 0; i < 10000; i++)
    {
        result += "Lets just concat a sentence on the end of it each time.";
    }
    return result;
}

So what I did was created a simple test method using a Stopwatch and benchmarked 5 runs of this method as follows.

public void IterationTest()
{
    string result = "";

    Stopwatch sw = new Stopwatch();
    sw.Start();
    result = LoopResultConcat(result);
    sw.Stop();

    long elapsedTicks = sw.ElapsedTicks;
}

After 5 test runs these were the outcomes in Ticks.

Using string +=
Test 1 = 20234811
Test 2 = 19659463
Test 3 = 20091368
Test 4 = 19763153
Test 5 = 19698219

Going through the test it didn’t seem to bad considering how many characters and iterations were being taken into account.  However, lets switch it up and use a StringBuilder and do a .append() on the end string during the loop. That looks like this.

private string LoopResult(string result, StringBuilder sb)
{
    for (int i = 0; i < 10000; i++)
    {
        sb.Append("Lets just concat a sentence on the end of it each time.");
    }
    return sb.ToString();
}

This proved to have a substantial gain over the string += method. The results listed below show that using the .Append() method substantially increases the processing time of building the extremely long string.

Using StringBuilder.Append()
Test 1 = 11198
Test 2 = 15684
Test 3 = 12751
Test 4 = 12646
Test 5 = 11763

As a side note, in our main IterationTest() method we will instantiate our new StringBuilder object with a designated capacity.  The StringBuilder object gets allocated a specific capacity, 16 characters when its instantiated; then it gets re-allocated each time it reaches its limit.  That is why we set the capacity we will need upfront so that it will not have to be re-allocated at all in the process.

StringBuilder sb = new StringBuilder(550080);

These are some of the many things to consider when dealing with rather large strings and the concatenating of strings. Overall, we can see that StringBuilder is a lot more performance conscious as well as it will leave less for the garbage collector to clean up in the process.


StackOverflow Profile