Reply
Passing parameters into thread constructor method
Replies: 0   Views: 3889  Subscribers: 0

Posted by Justin · 24-04-2012 - 22:08

Edited by reece · 12-11-2012 - 04:43
Hello everyone, a very useful and overlooked concept in C# is passing thread constructor parameters. If you find yourself   creating threads for simple tasks whilst making several repetitive methods and fields(class scoped variables) in the process then you know how unintuitive it is. Fortunately there is a solution to solve these thread constructor method parameters and the repetitive methods that follow in one implementation.

The answer, anonymous methods. Picture a method in a method, the concept is as simple as that. They have no signature or return type, just a body. But there is a specific time when these anonymous methods are necessary. So lets give some example code comparison.
Normal thread initialization: 
­
Thread thr = new Thread(ExampleMethod); // void method
thr.Start();­
In the above example we create a thread which requires a premade parameterless void method to be called in it's constructor. This has two undesired effects. 1.) Cannot pass any values into the method being called meaning that the method must be a non dynamic(specific to the thread calling it). The only way to make it dynamic and compare a condition would be to use a class scoped variable. 2.) A new class member(method) just for this thread must exist, regardless of the simplicity of the operations it will undergo. Without anonymous methods, there is no way around this undesired consequence of creating excess class members. The combination of the two caveats mentioned above together are what make it so bad, individually these two aspects are not bad at all since circumstances may call for them. But with that said, lets look at using anonymous methods inside of a thread. ­
Thread thr = new Thread(delegate()
{
    //method body
});
thr.Start();­
As you can see, a method is existing inside of the thread constructor. At first glance, the full benefits may not be noticed. We see the first notable advantage which is that we saved ourselves creating a whole new method as a class member. If a method is going to be non dynamic then why make it a class member? But that's the thing, anonymous methods also allow dynamism. Since a thread instantiation is within a method, local variables may exist and be accessed inside of the anonymous method. Lets see what that looks like: ­
private static void Example()
{
    bool sayCheese = true; //condition value
    Thread thr = new Thread(delegate()
    {
        if (sayCheese) //test condition
        {
            Console.WriteLine("Cheese");
        }
        else
        {
            Console.WriteLine("Not smiling for you");
        }
    });
    thr.Start();
}­
The above code snippet should be self explanatory, any variable from the parent method can be compared inside the anonymous one. Therefore, this creates a substantial alternative to passing parameters inside a thread method constructor. Anonymous methods are a great asset to the C# syntax and are often so great that they can be overused. I had a friend mentioned to me how often people can become reliant on these and end up in a huge nest of unreadable methods. So in most cases, I suggest to avoid this practice except where applicable. For example, one appropriate scenario for nested anonymous methods would be a thread in a thread where both threads have a simple task. However, even here this may not be best because if there is even the slight chance that you may need to reuse the same functionality of this nested anonymous method, then your saving alot of code to place it elsewhere in a class scope method which can be reused. With that said, use anonymous methods wisely. ( :­