0
using System;
using System.Threading;

namespace assignment_1_q2
{
    class program
    {
        public static int SumNumbers(int s, int e, int p)
        {
            switch (p)
            {
                case 1:



                    int nnsum = 0;
                    for (int i = s; i <= e; i++)
                    {
                        nnsum = nnsum + i;

                    }
                    Console.WriteLine("sum of natural numbers = {0}", nnsum);
                    break;

                case 2:


                    int nnsum1 = 0;
                    for (int i = s - 1; i <= e; i = i + 2)
                    {
                        nnsum1 = nnsum1 + i;

                    }
                    Console.WriteLine("sum of natural even numbers = {0}", nnsum1);
                    break;

                case 3:



                    int nnsum2 = 0;
                    for (int i = s; i <= e; i = i + 2)
                    {
                        nnsum = nnsum2 + i;

                    }
                    Console.WriteLine("sum of natural odd numbers = {0}", nnsum2);
                    break;
                default:
                    Console.WriteLine("no priority matches");
                    break;

            }
            return 0;
        }
        static void main(string[] args)
        {
            Thread t1 = new Thread(SumNumbers(1, 10, 1));
            Thread t2 = new Thread(SumNumbers(1, 10, 2));
            Thread t3 = new Thread(SumNumbers(1, 10, 3));
            t1.Start();
            t2.Start();
            t3.Start();

        }
    }
}

I am getting this error by simply passing arguments to method "SumNumbers".

Ryan M
  • 18,333
  • 31
  • 67
  • 74
akmaurya7
  • 5
  • 5

1 Answers1

3

You can use a lambda expression to pass parameters to your function

Thread t1 = new Thread(() => SumNumbers(1, 10, 2));
Thread t2 = new Thread(() => SumNumbers(1, 10, 2));
Thread t3 = new Thread(() => SumNumbers(1, 10, 3));

please take a look at this answer

ThreadStart with parameters

  • Thankyou so much for helping me out... – akmaurya7 Nov 12 '20 at 06:57
  • Sir, can you please explain the use of delegate using my code? – akmaurya7 Nov 12 '20 at 07:14
  • The problem was the passing of parameters, the Thread constructor it takes the delegate ParameterizedThreadStart as a parameter that only allows passing a single parameter (object type) to the start method, it is a limitation but we can use a lambda expression to pass all parameters to a function, in this case the function "SumNumbers" PS: I will update my answer. Please take a look at this answer https://stackoverflow.com/questions/1195896/threadstart-with-parameters – Mario Sandoval Nov 12 '20 at 17:44