user3806048
user3806048

Reputation: 73

How to keep a thread running and not terminate when a function finishes

I have this thread where I don't want it to terminate it self when it's finished a function. Instead I want to give it another function afterwards. `

t1 = new Thread(() => test());
t1.Start(); 
if(t1 finished the task )
{
   give t1 new task for exmp test2  
}

Upvotes: 1

Views: 854

Answers (2)

Matthew Watson
Matthew Watson

Reputation: 109732

If you are using .Net 4 or later, you can use a Task instead of a thread, then you can implement this using Task.ContinueWith().

Here's an example:

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    static class Program
    {
        private static void Main()
        {
            var task = Task.Run(() => task1());
            task = task.ContinueWith(antecedant => task2());

            Console.WriteLine("Waiting for composite task to complete.");
            task.Wait();
            Console.WriteLine("Composite Task completed.");
        }

        private static void task1()
        {
            Console.WriteLine("Starting task 1");
            Thread.Sleep(2000);
            Console.WriteLine("Ending task 1");
        }

        private static void task2()
        {
            Console.WriteLine("Starting task 2");
            Thread.Sleep(2000);
            Console.WriteLine("Ending task 2");
        }
    }
}

If you use this approach, you don't need to wait for the first task to complete before assigning it another one.

Upvotes: 0

Adil
Adil

Reputation: 148150

You can call both function in thread delegate like

t1 = new Thread(() =>{ test();test2();});

If you want to execute the test code repeatedly then you can use loop in Test(). You can also use Timer if you want to perform something repeatedly after any interval.

If you want to use your already created thread to save the thread creation cost then you can use ThreadPool

ThreadPool

Many applications create threads that spend a great deal of time in the sleeping state, waiting for an event to occur. Other threads might enter a sleeping state only to be awakened periodically to poll for a change or update status information. The thread pool enables you to use threads more efficiently by providing your application with a pool of worker threads that are managed by the system, MSDN.

Upvotes: 1

Related Questions