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

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.

One thought on “Multithreading with Parameters

  1. Pingback: Ensure Threads Have Finished Before Method Continues In CSharp | Adam Things

Leave a Reply

Your email address will not be published. Required fields are marked *

StackOverflow Profile