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.


JavaScript Closures

A JavaScript Closure is formed by returning a function object that was created within an execution context of a function call from that function call and assigning a reference to that inner function to a property of another object. Or by directly assigning a reference to such a function object to, for example, a global variable, a property of a globally accessible object or an object passed by reference as an argument to the outer function call.

In the example below you will notice that the globalVar has access to the exampleConcatReturn. However, it does not have access to the finishStringArg as that is seen as basically a private variable that cannot be accessed outside that function.

function exampleClosure(stringArg1, stringArg2) {
    var finishStringArg = "!";
    function exampleConcatReturn(innerArg) {
        return (stringArg1 + stringArg2 + innerArg + finishStringArg);
    }

    return exampleConcatReturn;
}

var globalVar = exampleClosure("Adam ", "Drummond "); /*stringArg1 = "Adam" and stringArg2 = Drummond*/

//Call to the function
alert(globalVar("Was Here")); /* innerArg = "Is Coding" */

/* would return Adam Drummond Was Here!*/

Another example is as follows.  This was based from Mozilla’s developers area.  I think it really does a great job in showing how the privateCounter is only used from within.  Also, you will take notice that you can create numerous functions off of the main makeCounter function and they will stay separate of each other.

var makeCounter = function () {
    var privateCounter = 0;
    function changeBy(val) {
        privateCounter += val;
    }
    return {
        increment: function () {
            changeBy(1);
        },
        decrement: function () {
            changeBy(-1);
        },
        value: function () {
            return privateCounter;
        }
    };
};

var Counter1 = makeCounter();
var Counter2 = makeCounter();

alert(Counter1.value()); /* Alerts 0 */

Counter1.increment();
Counter1.increment();

alert(Counter1.value()); /* Alerts 2 */

Counter1.decrement();

alert(Counter1.value()); /* Alerts 1 */

alert(Counter2.value()); /* Alerts 0: Notice that it doesn’t get affected by Counter1 */

As seen in this example, you have Counter1 and Counter2.  Take a look at the incrementing and decrementing of Counter1 and at the end, Counter2 is still in the same state as when it was created.


When to use Break and Continue

This is a fairly simple yet useful difference to know between break and continue when using loops or switch statements. The break statement terminates the closest enclosing loop or switch statement in which it appears. Control is passed to the statement that follows the terminated statement, if any.  The continue statement passes control to the next iteration of the enclosing iteration statement in which it appears.   I find this wording from msdn to be slightly confusing so let’s turn to some examples.

Take this loop for instance:

for (int i = 0; i < 100; i++)
{
    if (i == 0)
    {
        break;
    }

    TestMethod(i);
}

The use of break in the above example causes the loop to exit on the first iteration of the loop. This means that our TestMethod(i) will never be executed.  This works well if you are looking through a list for a particular value, once found, there is no need to iterate through everything else.

Now let’s take a look at the continue statement:

for (int i = 0; i < 10; i++)
{
    if (i == 0)
    {
        continue;
    }

    TestMethod(i);
}

The use of the continue statement above causes the loop to skip calling the TestMethod(i) when i  == 0.  However, the iterations will continue after that and TestMethod(i) will be executed when i  == 1 all the way to i == 99.  This comes in handy if there are certain values in a list that you are not wanting to execute on; you can skip over them and continue on with executing on the rest of the values in the list.

Some closing thoughts, in whether this is best practice or not it’s debating frequently.  The main argument that arises is code readability.  If you are having a hard time reading the code this will raise the chances of you exiting before you are wanting to and can cause bugs that you do not realize.  So as always, make sure you pay attention to what you are doing and what your intent is to ensure that your program is going to perform properly.


StackOverflow Profile