My requiremet is to abort the thread when the code takes more than 3 seconds to excecute. I am following the below method.

public static void Main(string[] args)
        {
            if (RunWithTimeout(LongRunningOperation, TimeSpan.FromMilliseconds(3000)))
            {
                Console.WriteLine("Worker thread finished.");
            }
            else
            {
                Console.WriteLine("Worker thread was aborted.");
            }

        }

        public static bool RunWithTimeout(ThreadStart threadStart, TimeSpan timeout)
        {
            Thread workerThread = new Thread(threadStart);

            workerThread.Start();

            bool finished = workerThread.Join(timeout);
            if (!finished)
                workerThread.Abort();

            return finished;
        }

        public static void LongRunningOperation()
        {
            Thread.Sleep(5000);
        }

Could ypu pleas tell me how can i do the same for the code having parameters? like below?

Public static Double LongRunningOperation(int a,int b)
{
}

You can use a ParameterizedThreadStart delegate like so:

Thread workerThread = new Thread(new ParameterizedThreadStart(LongRunningOperation);
workerThread.Start(a, b);

However note that the parameters a and b are passed as objects, not as int's so you will need to cast them inside your method.

public static Double LongRunningOperation(object a, object b)
{
   if (a.GetType() != typeof(Int32) || b.GetType() != typeof(Int32))
     throw new ArgumentException("An error occurred with the type of arguments passed!");

   int aValue = Convert.ToInt32(a);
   int bValue = Convert.ToInt32(b);

   // do something meaningful here...
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.